#
# 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, see <http://www.gnu.org/licenses/>.
#
"""
Evolve database to generation 1.

Moves dublincore settings to actual object attributes, then
remove dublincore from annotations.
"""

from zope.annotation.interfaces import IAnnotations
from zope.app.generations.utility import getRootFolder
from zope.dublincore.annotatableadapter import DCkey
from zope.dublincore.interfaces import IZopeDublinCore
from zope.security.proxy import removeSecurityProxy

from schooltool.contact.interfaces import IContact
from schooltool.intervention.interfaces import IInterventionGoal


def fixDublinCore(obj, persons):
    dublin = IZopeDublinCore(obj)
    if IInterventionGoal.providedBy(obj):
        creator = dublin.creators[0].split('.')[2]
        if creator in persons:
            obj.creator.add(IContact(persons[creator]))
    obj.created = dublin.created
    del IAnnotations(obj)[DCkey]


def evolve(context):
    """Moves dublincore settings to actual object attributes, then
       remove dublincore from annotations."""

    app = getRootFolder(context)
    interventionRoot = app.get(u'schooltool.interventions', {})
    persons = app.get(u'persons', {})
    for schoolYear in interventionRoot.values():
        for student in schoolYear.values():
            for message in student['messages'].values():
                fixDublinCore(message, persons)
            for goal in student['goals'].values():
                fixDublinCore(goal, persons)

