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

import expression.core.dataholders as dataholders
import expression.core.documents as documents
import expression.core.elements as elements
import expression.core.environs as environs
import expression.core.filesystems as filesystems
import expression.core.namespaces as namespaces
import expression.core.strings as strings


class LanguageRedirect(elements.Element):
    def styled(self):
        languages = environs.getVar("readLanguages")
        if not languages:
            languages = []
        try:
            languages.append(self.evaluateXpath("yep:default")[0].content)
        except:
            pass

        rootItems = environs.getVar("rootStation").getItemLocations()
        for lang in languages:
            if lang in rootItems:
                return environs.getVar("httpRequestHandler").outputRedirect('/%s/' % lang)
        
        return environs.getVar("httpRequestHandler").outputErrorNotFound(None)


class Redirect(elements.Element):
    def styled(self):
        url = self.evaluateXpath("yep:location")[0].content
        try:
            type = self.evaluateXpath("yep:type")[0].content
        except:
            type = "302" # default to temporary

        if type == "301":
            return environs.getVar("httpRequestHandler").outputRedirectPermanent(url)
        else:
            return environs.getVar("httpRequestHandler").outputRedirect(url)

elements.registerElement(namespaces.yep.uri, "language-redirect", LanguageRedirect)
elements.registerElement(namespaces.yep.uri, "redirect", Redirect)
