from django.conf import settings

from zammad_py import ZammadAPI

from bursary.models import Bursary
from register.forms.misc import MiscForm
from register.models.attendee import Attendee
from register.views.core import RegisterStep


class MiscView(RegisterStep):
    title = 'Anything Else?'
    form_class = MiscForm

    def get_initial(self):
        user = self.request.user
        initial = {
            'notes': self.request.user.attendee.notes
        }
        try:
            bursary = user.bursary
        except Bursary.DoesNotExist:
            pass
        else:
            for field in bursary._meta.get_fields():
                if field.is_relation:
                    continue
                initial[field.name] = getattr(bursary, field.name)
        return initial

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['contributions'] = self.request_contributions()
        return kwargs

    def request_contributions(self):
        user = self.request.user
        try:
            bursary = user.bursary
        except Bursary.DoesNotExist:
            bursary = Bursary()
        return (
            settings.DEBCONF_REVIEW_FREE_ATTENDEES
            and not user.attendee.billable()
            and not bursary.potential_bursary())

    def create_or_update_zammad_ticket(self, user, notes):
        if not settings.ZAMMAD_URL:
            return

        client = ZammadAPI(url=settings.ZAMMAD_URL, http_token=settings.ZAMMAD_TOKEN)
        # Update the first existing ticket, if we find any
        for ticket in client.ticket.search(
            f"customer.email:{user.email} "
            f"AND tags:registration_notes "
            f'AND group.name:"Users::Registration"'
        ):
            if ticket["state"] != "open":
                client.ticket.update(ticket["id"], params={"state": "open"})
            client.ticket_article.create(params={
                "ticket_id": ticket["id"],
                "subject": f"Registration notes for {user.username}",
                "body": f"Registration was updated. The notes are now:\n{notes}",
                "content_type": "text/plain",
                "type": "note",
                "internal": False,
            })
            return
        ticket = client.ticket.create(params={
            "title": f"Registration notes for {user.username}",
            "group": "Users::Registration",
            "customer": user.email,
            "article": {
                "body": f"Registration notes:\n{notes}",
                "content_type": "text/plain",
                "type": "note",
                "internal": False,
            },
        })
        client.ticket_tag.add(ticket["id"], "registration_notes")

    def form_valid(self, form):
        user = self.request.user
        data = form.cleaned_data
        bursary_data = data.copy()
        attendee_data = {'notes': bursary_data.pop('notes')}
        bursary_data.update({
            'request_food': False,
            'request_accommodation': False,
            'request_travel': False,
            'request_expenses': False,
        })

        user.attendee  # We should never be creating, here
        if user.attendee.notes != attendee_data['notes']:
            self.create_or_update_zammad_ticket(user, attendee_data['notes'])
        user.attendee = Attendee.objects.update_or_create(
            user=user, defaults=attendee_data)[0]

        if self.request_contributions():
            user.bursary = Bursary.objects.update_or_create(
                user=user, defaults=bursary_data)[0]

        return super().form_valid(form)
