# -*- coding: UTF-8 -*-


# Expression
# By: Frederic Peters <fpeters@entrouvert.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#
# Copyright (C) 2004 Entr'ouvert, Frederic Peters & Emmanuel Raviart
#
# 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.


"""Questionnaires Module"""


import copy

import libxml2

import dataholders
import directories
import elements
import environs
import faults
import modules
import namespaces
import stations
import strings
import things


class MyQuestionnaire(things.Thing):
    pass
    #~ def walk1(self, uriPathFragments):
        #~ user = environs.getVar("user")
        #~ if user is None:
            #~ if uriPathFragments[-1] == 'exists':
                #~ return False
            #~ raise faults.PathUnauthorized("/".join(uriPathFragments))
        #~ try:
            #~ questionnaire = self.walkToLocation(
                #~ "/questionnaires/%s" % strings.simplify(user.email))
        #~ except faults.PathNotFound:
            #~ try:
                #~ questionnaireFeature = modules.getElementFeature(
                    #~ namespaces.yep.uri, "questionnaire")
            #~ except KeyError:
                #~ if uriPathFragments[-1] == 'exists':
                    #~ return False
                #~ raise faults.PathNotFound('/'.join(uriPathFragments))
            #~ questionnairesHolder = self.walkToLocation("/questionnaires/")
            #~ questionnaireHolder = questionnaireFeature.newXmlHolder(questionnairesHolder)
        #~ else:
            #~ questionnaireHolder = questionnaire.getDataHolder()
        #~ # Recreate a new holder for the questionnaire, with the same file path,
        #~ # but the uri of myQuestionnaire.
        #~ newUriStep = copy.copy(self.getDataHolder().resource.uriStep)
        #~ newUriStep.resource = None
        #~ newFileSystemStep = copy.copy(
            #~ questionnaireHolder.resource.fileSystemStep)
        #~ newFileSystemStep.resource = None
        #~ newFileSystemHierarchicalStep = copy.copy(
            #~ questionnaireHolder.resource.fileSystemHierarchicalStep)
        #~ newFileSystemHierarchicalStep.resource = None
        #~ newResource = resources.LocalResource(
            #~ newUriStep, newFileSystemStep, newFileSystemHierarchicalStep)
        #~ newHolder = dataholders.XmlHolder(newResource)
        #~ newHolder.node = questionnaireHolder.node
        #~ newHolder.isTemporary = True
        #~ newHolder.setupDataHolder()
        #~ return newHolder.walk(uriPathFragments)


class Questionnaire(things.Thing):
##     def doHttpGet(self, modeName, uriPathFragments, function, *arguments, **keywords):
##         if modeName == "view" and self.estValide:
##             modeName = "view-valide"
##             environs.setVar("pageName", modeName)
##         return things.Thing.doHttpGet(
##             self, modeName, uriPathFragments, function, *arguments, **keywords)

    def getEstValide(self):
        nodes = self.evaluateXpath("yep:estValide")
        if not nodes:
            return None
        content = nodes[0].content
        if not content:
            return None
        return content not in ("0", "false") 

    def getNomCollectivite(self):
        nodes = self.evaluateXpath("yep:nomCollectivite")
        if not nodes:
            return None
        #return unicode(nodes[0].content, "UTF-8")
        return nodes[0].content

    def getSimpleLabel(self):
        return self.nomCollectivite

##     def modeAccessIsAuthorized(self, modeName):
##         # if modeName in ("edit", "new", "submit", "view", "view-all"):
##         if True:
##             # To use a questionnaire, the user must be logged, and its
##             # questionnaire should not exist yet.
##             user = environs.getVar("user")
##             if user is None:
##                 return False
##             if strings.simplify(user.email) == self.getDataHolder().localId:
##                 # FIXME: Forbid everything except "view" once the registration
##                 # is closed.
##                 if self.estValide:
##                     return not modeName.startswith("edit") \
##                         and modeName not in ("submit",)
##                 return True # modeName == "view" or registration date is not over.
##             elif modeName in ("new", "submit") \
##                     and self.getDataHolder().localId == "new-yep-questionnaire":
##                 return True
##             administrators = self.getAdministrators()
##             return administrators is not None and administrators.containsUser()
##         return things.Thing.modeAccessIsAuthorized(self, modeName)

    estValide = property(getEstValide)
    nomCollectivite = property(getNomCollectivite)
    simpleLabel = property(getSimpleLabel)


class Questionnaires(directories.Directory):
##     def modeAccessIsAuthorized(self, modeName):
##         if modeName == "new-yep-questionnaire":
##             # To create a questionnaire, the user must be logged, and its
##             # questionnaire should not exist yet.
##             user = environs.getVar("user")
##             if user is None:
##                 return False
##             return not self.walk(
##                 [strings.simplify(user.email)], None, "existsAndIsAuthorized")
##         return directories.Directory.modeAccessIsAuthorized(self, modeName)

    # FIXME: TODO: To move to QuestionnairesHolder...
    def newItemLocalId(self):
        user = environs.getVar("user")
        return  strings.simplify(user.email)


elements.registerElement(namespaces.yep.uri, "myQuestionnaire", MyQuestionnaire)
elements.registerElement(
    namespaces.yep.uri, "questionnaire", Questionnaire,
    "http://www.entrouvert.org/expression/schemas/Questionnaire.xsd",
    "http://www.entrouvert.org/expression/descriptions/Questionnaire.xml")
elements.registerElement(namespaces.yep.uri, "questionnaires", Questionnaires)
