# -*- 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.


"""Widgets Module

Widgets are XML elements that can be converted to visible HTML elements.
"""


class WidgetMixin(object):
    def getBind(self, context, modelContext):
        parent = self.getParent()
        if parent is None:
            return None
        return parent.getBind(context, modelContext)

    def getChildInstanceDataXpath(self, context, modelContext):
        return self.getInstanceDataXpath(context, modelContext)

    def getInstanceDataXpath(self, context, modelContext):
        parent = self.getParent()
        if parent is None:
            return ""
        else:
            return self.getParent().getChildInstanceDataXpath(context, modelContext)

    def getModel(self, context):
        return self.getModelContext(context).prototype

    def getModelContext(self, context):
        modelId = self.modelId
        if modelId is not None and context.xformsModelsById is not None \
               and modelId in context.xformsModelsById:
            modelContext = context.xformsModelsById[modelId]
        else:
            modelContext = context.xformsDefaultModel
        return modelContext

    def getModelId(self):
        if self.getParent() is None:
            return None
        return self.getParent().modelId

    def getRootInstanceDataXpath(self, context, modelContext):
        xpath = self.getInstanceDataXpath(context, modelContext)
        embedderContext = modelContext.embedderContext
        if embedderContext is None:
            return xpath
        embedder = modelContext.embedder
        embedderModelContext = embedder.getModelContext(embedderContext)
        embedderXpath = embedder.getRootInstanceDataXpath(embedderContext, embedderModelContext)
        if embedderXpath and xpath:
            return "%s/%s" % (embedderXpath, xpath)
        else:
            return "%s%s" % (embedderXpath, xpath)

    def submit(self):
        widgetNodes = self.evaluateXpath("*")
        for widgetNode in widgetNodes:
            widget = self.newElement(widgetNode)
            widget.submit()

    modelId = property(getModelId)
