#
# SchoolTool - common information systems platform for school administration
# Copyright (c) 2009 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 4.

Fix goals to copy persons_responsible to newly created at_one_time_responsible
attribute as well as the internal attribute, _persons_responsible, that is
used to store the value for what is now a persons_responsible get/set property.
"""

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


def fixAtOneTimeResponsible(obj):
    dir(obj)
    obj._persons_responsible = obj.__dict__['persons_responsible']
    del obj.__dict__['persons_responsible']
    obj.at_one_time_responsible = obj._persons_responsible


def evolve(context):
    """Copy persons_responsible to newly created at_one_time_responsible."""
    root = getRootFolder(context)

    old_site = getSite()
    apps = findObjectsProviding(root, ISchoolToolApplication)
    for app in apps:
        setSite(app)
        interventionRoot = app.get(u'schooltool.interventions', {})
        for schoolYear in interventionRoot.values():
            for student in schoolYear.values():
                for goal in student['goals'].values():
                    fixAtOneTimeResponsible(goal)

    setSite(old_site)
