import sform

from urllib.parse import urlparse

from django.conf import settings
from django.core.exceptions import ValidationError

from staff.departments.models import Department


def split(string):
    result = []
    for item in string.split(','):
        item = item.strip()
        if item:
            result.append(item)
    return result


class MaillistsForm(sform.SForm):
    maillist = sform.CharField(max_length=128, default='')


class ClubsForm(sform.SForm):
    club = sform.CharField(max_length=128, default='')


class ShortEditForm(sform.SForm):
    description = sform.CharField(max_length=4096, default='')
    description_en = sform.CharField(max_length=4096, default='')

    wiki_page = sform.CharField(max_length=2048, default='')
    clubs = sform.GridField(sform.FieldsetField(ClubsForm))
    maillists = sform.GridField(sform.FieldsetField(MaillistsForm))

    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial')
        if initial:
            initial['maillists'] = [
                {'maillist': m} for m in split(initial['maillists'])
            ]
            initial['clubs'] = [
                {'club': m} for m in split(initial['clubs'])
            ]

        super(ShortEditForm, self).__init__(*args, **kwargs)

    def clean_wiki_page(self, value):
        if not value:
            return value

        parsed = urlparse(value)

        if (parsed.scheme or parsed.hostname) and parsed.hostname != settings.WIKI_HOST:
            raise ValidationError('Invalid wiki host', code='invalid')

        if parsed.path.startswith('/'):
            return parsed.path[1:]

        return parsed.path

    def clean(self):
        cd = self.cleaned_data
        cd['maillists'] = ','.join(r['maillist'] for r in cd['maillists'])
        cd['clubs'] = ','.join(r['club'] for r in cd['clubs'])
        return cd


class ExportAttendanceForm(sform.SForm):
    date_from = sform.DateField(state=sform.REQUIRED)
    date_to = sform.DateField(state=sform.REQUIRED)
    department = sform.ModelChoiceField(
        queryset=Department.objects.filter(intranet_status=1),
        state=sform.NORMAL,
        label_extractor='name',
    )
