import urllib.parse

from django import forms
from django.conf import settings
from django.utils.text import slugify


class DonateForm(forms.Form):
    DEFAULT_CUSTOM_AMOUNT = 1000
    ALLOWED_PERIODICITY = [730, 99999]
    PORTAL_ID_IN_SELECT = -1

    amount = forms.IntegerField(required=False)
    crowdfunding = forms.IntegerField(required=False)
    custom_amount = forms.IntegerField(required=False)
    periodicity = forms.IntegerField()
    portal_project_id = forms.IntegerField()
    product = forms.CharField(required=False)
    select_portal_project_id = forms.IntegerField(required=False)

    def clean_periodicity(self):
        value = self.cleaned_data["periodicity"]
        if value not in self.ALLOWED_PERIODICITY:
            raise forms.ValidationError("Wrong periodicity!")
        if self.cleaned_data["crowdfunding"] and value != 99999:
            raise forms.ValidationError("Wrong periodicity!")
        return value

    def clean(self):
        cleaned_data = super().clean()
        if (
            cleaned_data["portal_project_id"] == self.PORTAL_ID_IN_SELECT
            and cleaned_data["select_portal_project_id"] is None
        ):
            raise forms.ValidationError("Není zadán účel daru.")
        if not cleaned_data["amount"] and not cleaned_data["custom_amount"]:
            raise forms.ValidationError("Nebyla zadána částka.")
        if cleaned_data["crowdfunding"] and not cleaned_data["product"]:
            raise forms.ValidationError("Nebyla zadána produkt.")
        if cleaned_data["product"] and not cleaned_data["crowdfunding"]:
            raise forms.ValidationError("Nebyla zadána typ odměny.")
        return cleaned_data

    def get_amount(self):
        amount = self.cleaned_data["amount"]
        if not amount:
            amount = (
                abs(self.cleaned_data["custom_amount"]) or self.DEFAULT_CUSTOM_AMOUNT
            )
        return amount

    def get_redirect_url(self):
        amount = self.get_amount()
        crowdfunding = self.cleaned_data["crowdfunding"]
        product = self.cleaned_data["product"]
        periodicity = self.cleaned_data["periodicity"]
        portal_project_id = self.cleaned_data["portal_project_id"]

        if portal_project_id == self.PORTAL_ID_IN_SELECT:
            portal_project_id = self.cleaned_data["select_portal_project_id"]

        query_dict = {
            "amount": amount,
            "periodicity": periodicity,
            "projectAccount": portal_project_id,
            "source": settings.DONATE_PORTAL_REDIRECT_SOURCE,
        }

        if crowdfunding:
            product = slugify(product)
            query_dict.update(crowdfunding=crowdfunding, product=product)

        query = urllib.parse.urlencode(query_dict)

        return f"{settings.DONATE_PORTAL_REDIRECT_URL}?{query}"