import os
import subprocess
from django.db import models
from django.urls import reverse
from django.conf import settings
from poetry.utils import get_hash


class Poet(models.Model):
    name = models.CharField(max_length=50)
    path = models.CharField(max_length=255)
    slug = models.SlugField(max_length=50, unique=True, db_index=True)
    author = models.CharField(max_length=128, blank=True)
    url = models.CharField(max_length=255, blank=True)
    description = models.TextField(blank=True)
    first_line_title = models.BooleanField(default=False)
    skip_first_lines = models.IntegerField(default=0)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('poetry_poet', kwargs={'slug': self.slug})

    def write(self):
        curdir = os.getcwd()
        os.chdir(os.path.dirname(self.path))
        proc = subprocess.Popen(self.path,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        os.chdir(curdir)
        stdout, stderr = proc.communicate()
        text = str(stdout, "utf-8", errors="ignore")[:1000]
        slug = get_hash(text)
        title = ''
        if self.first_line_title:
            title, text = text.split('\n', 1)
        if self.skip_first_lines:
            text = text.split('\n', self.skip_first_lines)[-1]
        text = text.strip('\n')
        poem = self.poem_set.create(
            slug=slug,
            text=text,
            title=title
            )
        return poem

    def make_for_contest(self):
        assert not self.poem_set.filter(for_contest=True).exists()
        for i in range(settings.POETRY_POEMS_FOR_CONTEST):
            p = self.write()
            p.for_contest = True
            p.save()
        return self.poem_set.filter(for_contest=True)

    def contest_poems(self):
        return self.poem_set.filter(in_contest=True)


class Poem(models.Model):
    slug = models.SlugField(max_length=50, db_index=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    text = models.TextField()
    poet = models.ForeignKey(Poet, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, editable=False, db_index=True)
    seen_at = models.DateTimeField(auto_now_add=True, editable=False)
    view_count = models.IntegerField(default=1)

    for_contest = models.BooleanField(default=False)
    in_contest = models.BooleanField(default=False)

    def __str__(self):
        oneliner = "%s, %s" % (self.poet.name, self.pretty_title())
        oneliner += " [%s…]" % (" ".join(self.text.split()[:5]))
        return oneliner

    def get_absolute_url(self):
        return reverse('poetry_poem', kwargs={'slug': self.slug})

    def pretty_title(self):
        return self.title or "***"

    def visit(self):
        self.view_count += 1
        self.seen_at = datetime.now()
        self.save()
