#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2005 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, see <http://www.gnu.org/licenses/>.
#

import pytz
from persistent import Persistent
from datetime import datetime

from zope.annotation.interfaces import IAttributeAnnotatable
from zope.container.contained import Contained
from zope.container.btree import BTreeContainer
from zope.interface import implements
from zope.publisher.interfaces import IRequest
from zope.publisher.browser import TestRequest
from zope.security import management
from zope.security.proxy import removeSecurityProxy

from schooltool.contact.interfaces import IContact
from schooltool.relationship import RelationshipProperty
from schooltool.relationship.uri import URIObject

import interfaces


URICreator = URIObject(
    'http://schooltool.org/ns/intervention/creator',
    'Creator', 'The creator/sender of the intervention relationship.')
URIResponsible = URIObject(
    'http://schooltool.org/ns/intervention/responsible',
    'Responsible', 'The persons responsible relationship.')
URIAtOneTime = URIObject(
    'http://schooltool.org/ns/intervention/atonetime',
    'AtOneTime', 'The at one time responsible relationship.')
URIMessage = URIObject(
    'http://schooltool.org/ns/intervention/message',
    'Message', 'The intervention message.')
URIGoal = URIObject(
    'http://schooltool.org/ns/intervention/goal',
    'Goal', 'The intervention goal.')
URIContact = URIObject(
    'http://schooltool.org/ns/intervention/contact',
    'Contact', 'The contact being linked.')


def getRequest():
    """Return the request object for the current request.
       In the case of unit testing, return a TestRequest instance."""

    i = management.getInteraction()
    for p in i.participations:
        if IRequest.providedBy(p):
            return p
    return TestRequest()


def contactName(contact):
    contact = removeSecurityProxy(contact)
    return '%s %s' % (contact.first_name, contact.last_name)


def contactsName(contacts):
    contacts = [removeSecurityProxy(c) for c in contacts]
    unsorted = [((c.last_name, c.first_name), contactName(c)) 
                 for c in contacts]
    return [name for sort, name in sorted(unsorted)]


def contactsEmail(contacts):
    return sorted([contact.email for contact in contacts if contact.email])


class InterventionRoot(BTreeContainer):
    """Container of InterventionSchoolYear objects."""

    implements(interfaces.IInterventionRoot)


class InterventionSchoolYear(BTreeContainer):
    """Container of InteventionStudent objects."""

    implements(interfaces.IInterventionSchoolYear)


class InterventionStudent(BTreeContainer):
    """Container of the student's intervention containers."""

    implements(interfaces.IInterventionStudent)

    def __init__(self):
        super(InterventionStudent, self).__init__()


class InterventionMessages(BTreeContainer):
    """Container of Tier1 InteventionMessage objects."""

    implements(interfaces.IInterventionMessages)


class InterventionMessage(Persistent, Contained):
    """Intervention message about a given student."""

    implements(interfaces.IInterventionMessage, IAttributeAnnotatable)

    subject = None
    created = None

    sender = RelationshipProperty(URICreator, URIMessage, URIContact)

    recipients = RelationshipProperty(URIResponsible, URIMessage,
                                      URIContact)

    def __init__(self, body, subject=None, status_change=False):
        self.subject = subject
        self.body = body
        self.status_change = status_change
        self.created = pytz.UTC.localize(datetime.utcnow())


class InterventionGoals(BTreeContainer):
    """Container of InterventionGoal objects."""

    implements(interfaces.IInterventionGoals)


class InterventionGoal(Persistent, Contained):
    """Intervention goal for a given student."""
    implements(interfaces.IInterventionGoal, IAttributeAnnotatable)

    created = None

    creator = RelationshipProperty(URICreator, URIGoal, URIContact)

    _persons_responsible = RelationshipProperty(URIResponsible, URIGoal,
                                               URIContact)

    at_one_time_responsible = RelationshipProperty(URIAtOneTime, URIGoal,
                                                   URIContact)

    def __init__(self, goal, timeline,
                 presenting_concerns=u'', strengths=u'', indicators=u'',
                 intervention=u'', goal_met=False,
                 follow_up_notes=u''):
        self.presenting_concerns = presenting_concerns
        self.goal = goal
        self.strengths = strengths
        self.indicators = indicators
        self.intervention = intervention
        self.timeline = timeline
        self.goal_met = goal_met
        self.follow_up_notes = follow_up_notes
        self.notified = False
        self.created = pytz.UTC.localize(datetime.utcnow())

    @property
    def persons_responsible(self):
        return self._persons_responsible

    @persons_responsible.setter
    def persons_responsible(self, value):
        contacts = [IContact(contact) for contact in value]
        for contact in self._persons_responsible:
            if contact not in contacts:
                self._persons_responsible.remove(contact)
        for contact in contacts:
            if contact not in self._persons_responsible:
                self._persons_responsible.add(contact)
            if contact not in self.at_one_time_responsible:
                self.at_one_time_responsible.add(contact)
