# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
from django.template.loader import get_template
# from mezzanine.pages.models import Page
# from mezzanine.core.models import RichText
from djrichtextfield.models import RichTextField

import datetime
from djphys.funcs import short_story

# Create your models here.


class NewsItem(models.Model):
    NEWSTYPES = (
        ('s', 'Story'),
        ('a', 'Announcement'),
        ('e', 'Event'),
        ('u', 'Unique'),  # for the middle column of the landing page
        ('p', 'People'),  # for the People panel on the landing page
        ('k', 'Kiosk'),  # for utility links at the bottom right
        ('P', 'Profile'),
        ('A', 'Alumni'),
        ('S', 'Statement'),
    )
    category = models.CharField(
        max_length=1,
        choices=NEWSTYPES,
        help_text="Unique, People, and Kiosk have special roles on the landing page")
    date = models.DateField()
    post_date = models.DateField(auto_now_add=True)
    stop_date = models.DateField(null=True, blank=True)
    author = User()
    headline = models.CharField(max_length=200)
    text = RichTextField()
    location = models.CharField(max_length=64, blank=True, null=True)
    keywords = models.CharField(max_length=100, blank=True)
    picture = models.ImageField(upload_to='stories', blank=True, null=True)

    @classmethod
    def export(NewsItem):
        from djphys.export import Exporter
        xp = Exporter(
            NewsItem,
            "id;type;date;post_date;stop_date;headline;text;location;picture".split(
                ';')
        )
        for i in NewsItem.objects.all():
            xp.write([
                str(i.id),
                i.get_category_display(),
                xp.date(i.date),
                xp.date(i.post_date),
                xp.date(i.stop_date),
                xp.text(i.headline),
                xp.text(i.text),
                xp.str(i.location),
                xp.xobject(i.picture, f'picture-{i.id:03d}')
            ])

    def __str__(self):
        return self.headline

    def short_date(self):
        return self.date.strftime("%m/%d/%y")

    def teaser(self):
        return short_story(self.text)

    def blurb(self, thumbsize="180x180"):
        temp = get_template('news/blurb.html')
        return mark_safe(temp.render({'story': self, 'thumbsize': thumbsize, }))

    def tile(self, thumbsize="180x180", **kwargs):
        """
        To modify behavior, kwargs can include 'header' and 'trailer'
        """
        temp = get_template('news/tile.html')
        params = {'story': self, 'thumbsize': thumbsize, }
        return mark_safe(temp.render({**params, **kwargs}))

    def story(self):
        temp = get_template('news/story.html')
        return mark_safe(temp.render({'story': self, }))

    class Meta:
        ordering = ['-date']


class RibbonAnnouncement(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    post_date = models.DateTimeField()
    stop_date = models.DateTimeField()
    message = models.CharField(max_length=128)
    url = models.CharField(max_length=128, blank=True,
                           null=True, help_text='Optional link')

    def __str__(self):
        return self.message

    class Meta:
        ordering = ['-post_date']


class Story(models.Model):
    date = models.DateField()
    post_date = models.DateField(auto_now_add=True)
    author = User()
    headline = models.CharField(max_length=200)
    text = RichTextField()
    keywords = models.CharField(max_length=100, blank=True)
    picture = models.ImageField(upload_to='stories', blank=True, null=True)

    def __str__(self):
        return self.headline

    def short_date(self):
        return self.date.strftime("%m/%d/%y")

    class Meta:
        ordering = ['-date']
        verbose_name_plural = "stories"


class Event(models.Model):
    date = models.DateTimeField()
    post_date = models.DateField(auto_now_add=True)
    author = User()
    headline = models.CharField(max_length=200)
    text = RichTextField()
    location = models.CharField(max_length=64, null=True)
    keywords = models.CharField(max_length=100, blank=True, null=True)
    picture = models.ImageField(upload_to='stories', blank=True, null=True)

    def __str__(self):
        return '{0} — {1}'.format(self.date, self.headline)

    def display(self):
        return '{0} — {1}'.format(self.date, self.headline)

    class Meta:
        ordering = ['-date']


# class MezzStory(Page, RichText):
    #post_date = models.DateField(auto_now_add=True)
    #author = User()
    #headline = models.CharField(max_length=200)
    #picture = models.ImageField(upload_to='stories', blank=True, null=True)


# class Announcement(models.Model):
    #start_date = models.DateField()
    #post_date = models.DateField(auto_now_add=True)
    #stop_date = models.DateField()
    #author = User()
    #headline = models.CharField(max_length=200)
    #text = RichTextField()
    #keywords = models.CharField(max_length=100, blank=True)
    #picture = models.ImageField(upload_to='stories', blank=True, null=True)

    # def __str__(self):
        # return self.headline

    # class Meta:
        #ordering = ['-start_date']


# def migrate_stories():
    # for s in Story.objects.all():
        # NewsItem.objects.create(category='s',
        # date=s.date,
        # post_date=s.post_date,
        # headline=s.headline,
        # text=s.text,
        # keywords=s.keywords,
        # picture=s.picture
        # )
    # for e in Event.objects.all():
        # NewsItem.objects.create(category='e',
        # date=e.date,
        # post_date=e.post_date,
        # headline=e.headline,
        # text=e.text,
        # keywords=e.keywords,
        # picture=e.picture,
        # location=e.location
        # )
    # for s in Announcement.objects.all():
        # NewsItem.objects.create(category='a',
        # date=s.start_date,
        # post_date=s.post_date,
        # stop_date=s.stop_date,
        # headline=s.headline,
        # text=s.text,
        # keywords=s.keywords,
        # picture=s.picture
        # )


def identify_images():
    import re
    for ns in NewsItem.objects.filter(picture="")[:10]:
        img = re.search("<img .*src=['\"]([^'\"]*)['\"].*>", ns.text)
        if img:
            print(
                "In {0} I found \n**************\n{1}\n*****************\n\n".format(ns.text, img.group(1)))

