# -*- coding: utf-8 -*-
import hashlib
import pickle

from django.db import models
from django.conf import settings

from events.translation.models import TranslationModel


class UserMessage(TranslationModel):
    FIELDS_FOR_TRANSLATION = ('name', 'text', 'label')

    name = models.CharField('Название новости', max_length=250)
    text = models.TextField('Текст новости')
    link = models.URLField('Ссылка для интерфейса', blank=True)
    enabled = models.BooleanField('Новость активна', default=False)
    label = models.CharField('Надпись на кнопке', max_length=250, blank=True, null=True)
    slug = models.SlugField('Строковый идентификатор', null=True)
    date_started = models.DateField('Начало периода', blank=True, null=True)
    date_finished = models.DateField('Конец периода', blank=True, null=True)
    show_count = models.PositiveIntegerField('Максимум показов', null=True)
    image = models.ForeignKey('media.Image', blank=True, null=True, on_delete=models.SET_NULL)

    class Meta:
        unique_together = ('slug', )

    def __str__(self):
        return '{} - {}'.format(self.name, self.link)


class Md5sumMixin(models.Model):
    md5sum = models.CharField(max_length=32, null=True, blank=True)

    class Meta:
        abstract = True

    @classmethod
    def _calc_md5sum(cls, *args, **kwargs):
        md5 = hashlib.md5()
        md5.update(pickle.dumps(args))
        md5.update(pickle.dumps(kwargs))
        return md5.hexdigest()


class AppType(models.Model):
    app_type = models.SlugField(max_length=30, primary_key=True)


class PermissionLog(models.Model):
    ASSIGN = 'assign'
    REMOVE = 'remove'
    CHANGE_TYPE_CHOICES = (
        (ASSIGN, ASSIGN),
        (REMOVE, REMOVE),
    )
    ROLE_NAME_CHOICES = (
        (settings.ROLE_SUPERUSER, 'superuser'),
        (settings.ROLE_SUPPORT, 'support'),
        (settings.ROLE_FORM_MANAGER, 'form manager'),
        (settings.ROLE_GROUP_MANAGER, 'group manager'),
    )

    request_user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='+')
    created = models.DateTimeField(auto_now_add=True, null=True)
    role_name = models.CharField(choices=ROLE_NAME_CHOICES, max_length=24)
    change_type = models.CharField(choices=CHANGE_TYPE_CHOICES, max_length=8)
    object_pk = models.CharField(null=True, max_length=24)
    user = models.ForeignKey('accounts.User', null=True, on_delete=models.CASCADE, related_name='+')
    group = models.ForeignKey('auth.Group', null=True, on_delete=models.CASCADE, related_name='+')
