# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.


from datetime import datetime

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _, ugettext, ungettext
from django.template.loader import render_to_string
from django.core import urlresolvers

from feincms import translations
from feincms.models import Base
from feincms.module.page.models import Page
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
from feincms.content.application.models import reverse
from feincms.module.medialibrary.fields import MediaFileForeignKey
from feincms.module.medialibrary.models import MediaFile
from feincms.module.page.extensions.navigation import NavigationExtension
from feincms.module.page.extensions.navigation import PagePretender
from feincms.content.application.models import ApplicationContent

from cloudcms.models import Application
from cloudcms.cms_utils import get_app_page

# monkeypatch django reverse (feincms 1.5+ solves this issue)
urlresolvers.reverse = reverse

class Category(models.Model, translations.TranslatedObjectMixin):
    """
    Question category.
    """

    ordering = models.SmallIntegerField(_('ordering'), default=0)
    display_on_menu = models.BooleanField(default=False)

    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')
        ordering = ['-ordering',]

    objects = translations.TranslatedObjectManager()

    def __unicode__(self):
        trans = translations.TranslatedObjectMixin.__unicode__(self)
        return trans or _('Unnamed category')


class CategoryTranslation(translations.Translation(Category)):
    """
    Category translation
    """
    title = models.CharField(_('category title'), max_length=100)
    slug = models.SlugField(_('slug'), unique=True)
    description = models.CharField(_('description'), max_length=250, blank=True)

    class Meta:
        verbose_name = _('category translation')
        verbose_name_plural = _('category translations')
        ordering = ['title']

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)

        super(CategoryTranslation, self).save(*args, **kwargs)


class QuestionManager(models.Manager):

    def active(self):
        return self.filter(is_active=True)

    def latest(self, limit=3):
        return self.filter()[:limit]


def get_faq_page():
    """
    Returns Page model that has been associated with faq application
    """
    return get_app_page(Page, "cloudcmsfaq")

class Question(Base):
    """
    Question/answer entry
    """
    is_active = models.BooleanField(_('is active'), default=True)
    is_featured = models.BooleanField(_('is featured'), default=False)

    title = models.CharField(_('title'), max_length=100)
    slug = models.SlugField(_('slug'), max_length=100, unique_for_date='published_on')
    author = models.ForeignKey(User, related_name='faqs', verbose_name=_('author'))
    language = models.CharField(max_length=255, choices=settings.LANGUAGES)

    application = models.ManyToManyField(Application,
            related_name="faqs",
            verbose_name=_('application'))

    published_on = models.DateTimeField(_('published on'), blank=True, null=True, default=datetime.now,
        help_text=_('Will be filled in automatically when question gets published.'))
    last_changed = models.DateTimeField(_('last change'), auto_now=True, editable=False)

    service = models.ForeignKey('cloudcms.Service', verbose_name=_('service'),
        related_name='faqs', null=True, blank=False)

    category = models.ForeignKey(Category, verbose_name=_('category'),
        related_name='faqs', null=False, blank=False)

    objects = QuestionManager()

    class Meta:
        get_latest_by = 'published_on'
        ordering = ['service', 'category', '-published_on']
        verbose_name = _('faq')
        verbose_name_plural = _('faqs')

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        try:
            r = reverse('cloudcmsfaq_question_detail', 'cloudcmsfaq.urls', (),
                    {
                     'service': self.service.translation.slug,
                     'slug': self.slug,
                    })
        except Exception, e:
            pass

        # ugly hack to fix proper application reverse url
        FAQ_URL = ""
        try:
            FAQ_URL = get_faq_page().get_navigation_url()
        except Exception, e:
            pass

        if r.startswith(FAQ_URL):
            return r
        else:
            return FAQ_URL + r.lstrip('/')

    def back_url(self):
        return get_faq_page().get_navigation_url()


# Feincms navigation extension
class FaqServicesNavigationExtension(NavigationExtension):
    """
    Navigation extension for FeinCMS which lists all categories that user
    wants to include in global site navigation.
    """

    name = _('faq categories')

    def children(self, page, **kwargs):
        from cloudcms.models import Service

        for service in Service.objects.filter(display_on_menu=True):
            url='%sservice/%s/' % (page.get_absolute_url(), service.translation.slug)
            yield PagePretender(
                title=service.translation.title,
                tree_id=page.tree_id,
                url=url,
                lft=0,
                rght=0,
                slug=category.translation.slug,
            )

