import logging

from django import forms
from django.core.exceptions import ValidationError

from staff.person.models import Staff

from staff.achievery.models import Achievement, TEXT_LENGTH_TINY, TEXT_LENGTH_SMALL

logger = logging.getLogger(__name__)


class CreateAchievementForm(forms.Form):

    title = forms.CharField(max_length=TEXT_LENGTH_SMALL)
    title_en = forms.CharField(max_length=TEXT_LENGTH_SMALL)

    description_short = forms.CharField(max_length=TEXT_LENGTH_SMALL, required=False)
    description_short_en = forms.CharField(max_length=TEXT_LENGTH_SMALL, required=False)

    description = forms.CharField(required=False)
    description_en = forms.CharField(required=False)

    service_name = forms.CharField(max_length=TEXT_LENGTH_SMALL)
    service_name_en = forms.CharField(max_length=TEXT_LENGTH_SMALL, required=False)

    category = forms.CharField(max_length=TEXT_LENGTH_TINY)

    icon_url = forms.CharField(required=False)

    creator_login = forms.CharField(required=False)

    def __init__(self, icon_required: bool, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.icon_required = icon_required

    def clean_title(self):
        title = self.cleaned_data['title']
        if Achievement.objects.filter(title=title).exists():
            raise ValidationError(
                f'Achievement {title} already exists, use other name',
                code='already-exists',
            )
        return title

    def clean_title_en(self):
        title_en = self.cleaned_data['title_en']
        if Achievement.objects.filter(title_en=title_en).exists():
            raise ValidationError(
                f'Achievement {title_en} already exists, use other name',
                code='already-exists',
            )
        return title_en

    def clean_icon_url(self):
        if not self.icon_required:
            return

        if not self.cleaned_data['icon_url']:
            raise ValidationError('Icon url is empty', code='invalid')

        return self.cleaned_data['icon_url']

    def clean_creator_login(self):
        if self.cleaned_data['creator_login']:
            try:
                self.cleaned_data['creator'] = Staff.objects.get(login=self.cleaned_data['creator_login'])
                return self.cleaned_data['creator_login']
            except Staff.DoesNotExist:
                raise ValidationError(f'User with login {self.cleaned_data["creator_login"]} does not exist')

    @property
    def achievement_data(self) -> dict:
        return {
            'title': self.cleaned_data['title'],
            'title_en': self.cleaned_data['title_en'],
            'description': self.cleaned_data['description'],
            'description_en': self.cleaned_data['description_en'],
            'description_short': self.cleaned_data['description_short'],
            'description_short_en': self.cleaned_data['description_short_en'],
            'description_html': self.cleaned_data['description'],
            'description_html_en': self.cleaned_data['description_en'],
            'service_name': self.cleaned_data['service_name'],
            'service_name_en': self.cleaned_data['service_name_en'],
            'category': self.cleaned_data['category'],
        }
