# w.c.s. - web application for online forms
# Copyright (C) 2005-2010  Entr'ouvert
#
# 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/>.

from quixote import get_publisher, get_response
from quixote.html import htmltext

from .qommon import _
from .qommon.storage import StorableObject
from .qommon.misc import simplify
from .qommon.substitution import Substitutions
from .qommon.xml_storage import XmlStorableObject

class Category(XmlStorableObject):
    _names = 'categories'
    _xml_tagname = 'category'
    name = None
    url_name = None
    description = None
    position = None
    redirect_url = None

    # declarations for serialization
    XML_NODES = [('name', 'str'), ('url_name', 'str'), ('description', 'str'),
            ('redirect_url', 'str'), ('position', 'int')]

    def __init__(self, name = None):
        StorableObject.__init__(self)
        self.name = name

    def migrate(self):
        changed = False

        if not self.url_name:
            self.url_name = simplify(self.name)
            changed = True

        if changed:
            self.store()

    @classmethod
    def get_by_urlname(cls, url_name):
        objects = [x for x in cls.select() if x.url_name == url_name]
        if objects:
            return objects[0]
        raise KeyError()

    @classmethod
    def has_urlname(cls, url_name):
        objects = [x for x in cls.select() if x.url_name == url_name]
        if objects:
            return True
        return False

    @classmethod
    def sort_by_position(cls, categories):
        # move categories with no defined position to the end
        categories.sort(key=lambda x: x.position if x and x.position is not None else 10000)

    def remove_self(self):
        from .formdef import FormDef
        for form in FormDef.select(lambda x: x.category_id == self.id):
            form.category_id = None
            form.store()
        StorableObject.remove_self(self)

    def get_substitution_variables(self, minimal=False):
        d = {
            'category_name': self.name,
            'category_id': self.url_name,
            'category_slug': self.url_name,
        }
        if not minimal:
            d.update({
                'category_description': self.description,
            })
        return d

    def get_url(self):
        base_url = get_publisher().get_frontoffice_url()
        return '%s/%s/' % (base_url, self.url_name)

    def get_description_html_text(self):
        if not self.description:
            return None
        text = self.description
        if text[0] != '<':
            text = '<p>%s</p>' % text
        return htmltext(text)


Substitutions.register('category_name', category=N_('General'), comment=N_('Category Name'))
Substitutions.register('category_description', category=N_('General'), comment=N_('Category Description'))
Substitutions.register('category_id', category=N_('General'), comment=N_('Category Identifier'))
