from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from webapp.models import BaseRole


# TODO: Move BaseRole to Kaehmt App; will fuck up the DB since table is removed, if no data migration is done before-hand.
# Either reconstruct all kaehmy roles from scratch then, or do these migrations:
# 1. Create table here
# 2. Data migrate from webapp BaseRole to new kaehmy BaseRole
# 3. Delete webapp BaseRole table

VERBOSE_NAME = _('Kaehmy')


class KaehmyBaseRole(BaseRole):
    """ABC"""

    CATEGORIES = (
        ('corporate', _('Corporate affairs')),
        ('freshman', _('Freshmen')),
        ('international', _('International')),
        ('external', _('External affairs')),
        ('media', _('Media')),
        ('tech', _('Technology')),
        ('wellbeing', _('Wellbeing')),
        ('elepaja', _('Elepaja')),
        ('ceremonies', _('Ceremonies')),
        ('studies', _('Studies')),
        ('sosso', _('Sössö magazine')),
        ('alumni', _('Alumni relations')),
        ('others', _('Others')),
    )
    category = models.CharField(_('Category'), choices=CATEGORIES, default='others', max_length=255)


class PresetRole(KaehmyBaseRole):
    """Model for kaehmy role."""

    description = models.TextField(_('Description'))

    class Meta:
        verbose_name = _('Preset kaehmy role')
        verbose_name_plural = _('Preset kaehmy roles')


class CustomRole(KaehmyBaseRole):
    """Model representing a user-specified custom occupation."""

    class Meta:
        verbose_name = _('Custom kaehmy role')
        verbose_name_plural = _('Custom kaehmy roles')


class CommentParent(models.Model):

    name = models.CharField(_('Name'), max_length=255, default='')
    email = models.EmailField(_('Email'), default='')
    timestamp = models.DateTimeField(_('Timestamp'), default=timezone.now)

    def __str__(self):
        return 'Message parent #{}'.format(self.id)


class Comment(CommentParent):
    """
    Model representing a kaehmymessage.

    Every message relates to certain kaehmyform or parent message.
    """

    class Meta:
        verbose_name = _('Kaehmykommentti')
        verbose_name_plural = _('Kaehmykommentit')

    message = models.TextField(_('Message'))
    parent = models.ForeignKey('CommentParent', related_name='messages', on_delete=models.CASCADE)


class Application(CommentParent):
    """
    Model representing a form for kaehmy.

    Allows user to choose from existing roles or to create custom ones.
    """
    YEAR_CHOICES = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, 'N'),
    )

    class Meta:
        verbose_name = _('Kaehmylomake')
        verbose_name_plural = _('Kaehmylomakkeet')

    phone_number = models.CharField(
        _('Phone number'), max_length=10, default="")
    year = models.IntegerField(_('Year'), choices=YEAR_CHOICES)
    text = models.TextField(_('Text'), default="", max_length=300)
    custom_role_name = models.CharField(
        _('Custom role name'), max_length=255, blank=True)
    custom_role_is_board = models.BooleanField(
        _('Board member'), blank=True)
    custom_roles = models.ManyToManyField(
        'kaehmy.CustomRole', related_name='forms', blank=True)
    preset_roles = models.ManyToManyField(
        'kaehmy.PresetRole', related_name='forms', blank=True)

    def __str__(self):
        """Return model info."""
        return _('Kaehmy application: {}').format(self.name)

    def comment_count(self):
        """Count comments for kaehmy."""
        total = 0

        def recurse(message):
            count = 0
            for msg in message.messages.all():
                count += recurse(msg)

            return count + 1

        for message in self.messages.all():
            total += recurse(message)

        return total

    def board_roles(self):
        presets = [r.name.capitalize() for r in self.preset_roles.filter(is_board=True)]
        customs = [r.name.capitalize() for r in self.custom_roles.filter(is_board=True)]
        combined = presets + customs
        return _('Board: {}').format(', '.join(combined)) if len(combined) > 0 else ''

    def official_roles(self):
        presets = [r.name.capitalize() for r in self.preset_roles.filter(is_board=False)]
        customs = [r.name.capitalize() for r in self.custom_roles.filter(is_board=False)]
        combined = presets + customs
        return _('Official: {}').format(', '.join(combined)) if len(combined) > 0 else ''

    def all_roles(self):
        presets = [r.name.capitalize() for r in self.preset_roles.all()]
        customs = [r.name.capitalize() for r in self.custom_roles.all()]
        combined = presets + customs
        return ', '.join(combined) if len(combined) > 0 else ''

    def has_any_board_role(self):
        return self.preset_roles.filter(is_board=True).exists() or self.custom_roles.filter(is_board=True)


# Telegram channel entry for Kaehmys
class TelegramChannel(models.Model):
    """Model containing the channel id of a Telegram chat"""

    class Meta:
        verbose_name = _('Telegram channel')
        verbose_name_plural = _('Telegram channels')

    name = models.CharField(max_length=255)
    channel_id = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return 'Telegram channel: "{}"'.format(self.name)
