#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2008 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
#
"""
Evolve database to generation 7.

Move message and goal id lists to new contact relationsship properties.
"""

import pytz

from zope.app.generations.utility import findObjectsProviding
from zope.app.generations.utility import getRootFolder
from zope.component.hooks import getSite, setSite

from schooltool.app.interfaces import ISchoolToolApplication
from schooltool.contact.interfaces import IContact, IContactable


def getContacts(ids, persons):
    for id in ids:
        if len(id) > 2 and id[-2] == ':':
            index = int(id[-1])
            id = id[:-2]
        else:
            index = 0
        if id not in persons:
            continue
        person = persons[id]
        if index:
            contacts = [contact for contact in IContactable(person).contacts]
            if index <= len(contacts):
                yield contacts[index - 1]
        else:
            yield IContact(person)


def fixMessage(message, persons):
    created = message.created  # activate __dict__
    if 'sender' in message.__dict__:
        message.created = created    # activate persistence
        sender_id = message.__dict__['sender']
        del message.__dict__['sender']
        for contact in getContacts([sender_id], persons):
            if contact not in message.sender:
                message.sender.add(contact)

    if 'recipients' in message.__dict__:
        message.created = created    # activate persistence
        recipient_ids = message.__dict__['recipients']
        del message.__dict__['recipients']
        for contact in getContacts(recipient_ids, persons):
            if contact not in message.recipients:
                message.recipients.add(contact)


def fixGoal(goal, persons):
    created = goal.created  # activate __dict__
    if 'creator' in goal.__dict__:
        goal.created = created    # activate persistence
        creator_id = goal.__dict__['creator']
        del goal.__dict__['creator']
        for contact in getContacts([creator_id], persons):
            if contact not in goal.creator:
                goal.creator.add(contact)

    if '_persons_responsible' in goal.__dict__:
        goal.created = created    # activate persistence
        responsible_ids = goal.__dict__['_persons_responsible']
        del goal.__dict__['_persons_responsible']
        for contact in getContacts(responsible_ids, persons):
            if contact not in goal._persons_responsible:
                goal._persons_responsible.add(contact)

    if 'at_one_time_responsible' in goal.__dict__:
        at_one_time_ids = goal.__dict__['at_one_time_responsible']
        del goal.__dict__['at_one_time_responsible']
        for contact in getContacts(at_one_time_ids, persons):
            goal.at_one_time_responsible.add(contact)


def evolve(context):
    root = getRootFolder(context)
    old_site = getSite()
    apps = findObjectsProviding(root, ISchoolToolApplication)

    for app in apps:
        setSite(app)
        interventionRoot = app.get(u'schooltool.interventions', {})
        persons = app.get('persons', {})
        for schoolYear in interventionRoot.values():
            for student in schoolYear.values():
                for message in student['messages'].values():
                    fixMessage(message, persons)
                for goal in student['goals'].values():
                    fixGoal(goal, persons)

