#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import pytz
from persistent import Persistent
from datetime import datetime
import rwproperty

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

from schooltool.intervention import InterventionGettext as _
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)

    created = None

    sender = RelationshipProperty(URICreator, URIMessage, URIContact)

    recipients = RelationshipProperty(URIResponsible, URIMessage,
                                      URIContact)

    def __init__(self, sender, recipients, body, status_change=False):
        if sender:
            self.sender.add(IContact(sender))
        for recipient in recipients:
            self.recipients.add(IContact(recipient))
        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, presenting_concerns, goal, strengths, indicators,
                 intervention, timeline, persons_responsible, goal_met=False,
                 follow_up_notes=u'', creator=None):
        self.presenting_concerns = presenting_concerns
        self.goal = goal
        self.strengths = strengths
        self.indicators = indicators
        self.intervention = intervention
        self.timeline = timeline
        self.persons_responsible = [IContact(p) for p in persons_responsible]
        self.goal_met = goal_met
        self.follow_up_notes = follow_up_notes
        self.notified = False
        if creator is not None:
            self.creator.add(IContact(creator))
        self.created = pytz.UTC.localize(datetime.utcnow())

    @rwproperty.getproperty
    def persons_responsible(self):
        return self._persons_responsible

    @rwproperty.setproperty
    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)

