# -*- coding: utf-8 -*-
from urlparse import urlparse
import os.path
from django.core.urlresolvers import resolve, Resolver404, reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from mptt.models import MPTTModel, TreeForeignKey, TreeManager


class PageManager(TreeManager):
    """
    Page custom manager
    """

    def get_active_page(self, uri):
        """
        Get current active page from request
        """
        try:
            page = self.get(url=unicode(uri), published=True)
        except Page.DoesNotExist:
            parsed = urlparse(uri)
            try:
                page = self.get(url=unicode(parsed.path), published=True)
            except Page.DoesNotExist:
                try:
                    page = self.get(url__startswith=unicode(parsed.path), published=True)
                except Page.DoesNotExist:
                    # try to find related page
                    try:
                        view_func = resolve(parsed.path).func
                        if hasattr(view_func, 'related_page_url'):
                            page = self.get_active_page(getattr(view_func, 'related_page_url'))
                        else:
                            raise
                    except Resolver404:
                        raise
        return page


class File(models.Model):
    """
    File attached to a page
    """
    name = models.CharField(_(u'name'), max_length=140, null=True, blank=True)
    file = models.FileField(_(u'file'), upload_to='staticpages')
    page = models.ForeignKey('Page', related_name='files')

    def __unicode__(self):
        return self.name

    @property
    def extension(self):
        return os.path.splitext(self.file.path)[1]


class PageImage(models.Model):
    """
    Image in page
    """
    title = models.CharField(_(u'title'), max_length=140, null=True, blank=True)
    image = models.FileField(_(u'image'), upload_to='staticpages')
    page = models.ForeignKey('Page', related_name='images')

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = _(u'image')
        verbose_name_plural = _(u'images')


class Page(MPTTModel):
    """Page"""
    name = models.CharField(_(u'name in the menu'), max_length=70)
    parent = TreeForeignKey('self', verbose_name=_(u'parent page'), null=True, blank=True, related_name='children')
    title = models.CharField(_(u'title tag'), max_length=255)
    url = models.CharField(_(u'url'), max_length=255,
                           help_text=_(u'Page full path: /news/ or /'), unique=True,
                           validators=[
                               RegexValidator('^/([a-z0-9-_A-Z]+/)*', message=_(u'Must start and end with slash'))])
    text = models.TextField(_(u'text'), blank=True, null=True, help_text=_(u'HTML content of the page if it is static'))
    template = models.CharField(_(u'template'), choices=[('default', _(u'Default')), ('wholesale', _(u'Wholesale'))],
                                default='default', max_length=10)
    published = models.BooleanField(_(u'published'),
                                    help_text=_(u'The page will not be shown at the site until it is published'),
                                    db_index=True, default=False)
    meta_keywords = models.TextField(_(u'meta keywords'), blank=True, null=True)
    meta_description = models.TextField(_(u'meta description'), blank=True, null=True)
    position = models.PositiveSmallIntegerField("Position", null=False, default=0)

    objects = PageManager()

    class MPTTMeta:
        order_insertion_by = ['position']

    def get_absolute_url(self):
        return self.url

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _(u'page')
        verbose_name_plural = _(u'pages')
        ordering = ['position']

