from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _

from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from django_extensions.db.models import TimeStampedModel
from historical.managers import PublishedManager
from newsroom.models import Story, WebEdition

try:
    from adzone.models import Advertiser, BannerAd

    ADVERTISER_FIELD = models.ForeignKey(Advertiser, blank=True, null=True)
    ADVERT_FIELD = models.ForeignKey(BannerAd, blank=True, null=True)
except:
    ADVERTISER_FIELD = models.CharField(
        _("Advertiser"), blank=True, null=True, max_length=140
    )
    ADVERT_FIELD = models.ImageField(
        _("Advertisment"), blank=True, null=True, upload_to="historical/ads/"
    )


class PublishModel(TimeStampedModel):
    published = models.BooleanField(_("Published"), default=False)
    published_on = models.DateTimeField(_("Published on"), default=datetime.now())

    objects = PublishedManager()

    class Meta:
        abstract = True


class Group(PublishModel):
    """Group model.
    Holds historical objects for organizational purposes."""

    title = models.CharField(_("Title"), max_length=140)
    slug = models.SlugField(_("Slug"), unique=True)
    graphic = models.ImageField(
        _("Graphic"), upload_to="historical/group/", blank=True, null=True
    )
    description = models.TextField(_("Description"), blank=True, null=True)
    sites = models.ManyToManyField(Site)
    template_name = models.CharField(
        _("template name"),
        max_length=200,
        blank=True,
        help_text=_(
            "Example: 'historical/group/special_history_section.html'. If this isn't provided, the system will use 'historical/group/default.html'."
        ),
    )
    created_by = models.ForeignKey(User, editable=False)

    class Meta:
        ordering = ("title",)
        verbose_name = _("Group")
        verbose_name_plural = _("Groups")

    def __unicode__(self):
        return u"%s" % (self.title)

    @models.permalink
    def get_absolute_url(self):
        return ("hi-group-detail", None, {"slug": self.slug})


class HistoricArticle(PublishModel):
    """Historic Article model.
       An historic article, belongs to a group and holds a story and an advertiser."""

    story = models.ForeignKey(Story)
    group = models.ForeignKey(Group)
    edition = models.ForeignKey(WebEdition, blank=True, null=True)
    description = models.TextField(_("Description"), blank=True, null=True)
    # advertisment=models.ImageField(_('Ad'), blank=True, null=True, upload_to='historical/ads/')
    advert = ADVERT_FIELD
    advertiser = ADVERTISER_FIELD
    view_count = models.PositiveIntegerField(default=0, editable=False)
    created_by = models.ForeignKey(User, editable=False)

    class Meta:
        ordering = ("published_on",)
        verbose_name = _("Historic article")
        verbose_name_plural = _("Historic articles")

    def __unicode__(self):
        return u"%s" % self.story.web_hed

    @models.permalink
    def get_absolute_url(self, site=""):
        return (
            "hi-article-detail",
            (),
            {
                "group_slug": self.group.slug,
                "year": self.story.published_on.year,
                "month": self.story.published_on.strftime("%b").lower(),
                "day": self.story.published_on.day,
                "slug": self.story.slug,
            },
        )
