#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2007 Shuttleworth Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
"""
Sources and vocabularies for form fields.

"""
from zope.component import queryUtility
from zope.interface import implements
from zope.schema.interfaces import ITitledTokenizedTerm

from schooltool.app.interfaces import ISchoolToolApplication
from schooltool.basicperson.interfaces import IBasicPersonSource
from schooltool.group.interfaces import IGroupContainer
from schooltool.schoolyear.interfaces import ISchoolYear
from schooltool.term.interfaces import IDateManager


class AdvisorTerm(object):
    """A term for displaying a person."""
    implements(ITitledTokenizedTerm)

    def __init__(self, value):
        if value:
            person = ISchoolToolApplication(None)['persons'][value]
            self.title = '%s %s' % (person.first_name, person.last_name)
        else:
            self.title = ''
        self.token = value
        self.value = value


class AdvisorSource(object):
    implements(IBasicPersonSource)

    def __init__(self, context):
        self.context = context

    def __contains__(self, value):
        return True

    def __len__(self):
        return len(self.context.groups)

    def __iter__(self):
        term = queryUtility(IDateManager).current_term
        groups = IGroupContainer(ISchoolYear(term))
        persons = set(groups['teachers'].members).union(
            set(groups['administrators'].members))
        persons = sorted(persons, key=lambda p: (p.last_name, p.first_name))
        for person in persons:
            yield AdvisorTerm(person.username)

    def getTermByToken(self, token):
        return AdvisorTerm(token)

    def getTerm(self, value):
        return AdvisorTerm(value)


def advisorVocabularyFactory():
    return AdvisorSource
