from django import forms
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.forms import ModelForm
from djconfig.forms import ConfigForm
from pyrogram.errors import ChannelPrivate

from config.utils import parse_mtproto_chat
from .client import get_client
from .models import AggregationSource, Chat


class AggregationSourceForm(ModelForm):
    invite_link = forms.CharField(help_text='Invite link (with joinchat) or username')

    def clean(self):
        cleaned_data = super(AggregationSourceForm, self).clean()
        invite_link = cleaned_data.pop('invite_link')
        if invite_link:
            with get_client() as app:
                try:
                    upd = app.join_chat(invite_link)
                except ChannelPrivate:
                    raise ValidationError('I was banned in this chat')
                chat = parse_mtproto_chat(app, upd.chats[0])
                cleaned_data['chat_id'] = chat.id
                Chat.from_obj(chat, app)
        return cleaned_data

    class Meta:
        model = AggregationSource
        fields = 'title', 'invite_link',


class AggregationSourceEditForm(AggregationSourceForm):
    invite_link = forms.CharField(help_text='Invite link (with joinchat) or username; '
                                            'leave empty if change is not needed', required=False)


class AggregatorAppConfigForm(ConfigForm):
    slug = 'aggregator'
    title = 'Aggregator'

    pyrogram_app_id = forms.CharField()
    pyrogram_app_hash = forms.CharField()
    pyrogram_app_version = forms.CharField(required=False)
    pyrogram_device_model = forms.CharField(required=False)
    pyrogram_system_version = forms.CharField(required=False)
    pyrogram_session = forms.FileField()

    def save_session(self):
        session = self.cleaned_data.get('pyrogram_session')
        if session:
            session.name = default_storage.save(session.name, session)

    def save(self):
        self.save_session()
        super(AggregatorAppConfigForm, self).save()
