# -*- coding: utf-8 -*-
from __future__ import annotations

import http
import logging

from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import FormView
from django_htmx.http import trigger_client_event

from hotpocket_backend.apps.accounts.mixins import AccountRequiredMixin
from hotpocket_backend.apps.ui.forms.saves import CreateForm
from hotpocket_backend.apps.ui.services import UISavesService
from hotpocket_backend.apps.ui.services.workflows import CreateSaveWorkflow

LOGGER = logging.getLogger(__name__)


class CreateView(AccountRequiredMixin, FormView):
    template_name = 'ui/saves/create.html'
    form_class = CreateForm

    def form_valid(self, form: CreateForm) -> HttpResponse:
        return CreateSaveWorkflow().run(
            request=self.request,
            account=self.request.user,
            url=form.cleaned_data['url'],
        )

    def get_success_url(self) -> str:
        return reverse('ui.associations.browse')


def embed(request: HttpRequest) -> HttpResponse:
    try:
        assert request.method == http.HTTPMethod.POST, (
            f'405 Method Not Allowed: `{request.method}`'
        )
        assert 'pk' in request.POST, (
            '400 Bad Request: `pk` missing'
        )
        assert request.htmx, (
            '400 Bad Reqquest: Not an HTMX request'
        )
    except AssertionError as exception:
        LOGGER.error(
            'Unable to render save embed: pk=`pk`: %s',
            exception,
            exc_info=exception,
        )
        return HttpResponse(
            b'NOPE',
            status=http.HTTPStatus.BAD_REQUEST,
            content_type='text/plain;charset=utf-8',
        )

    save = UISavesService().get_or_404(pk=request.POST['pk'])

    response = render(
        request,
        'ui/saves/partials/embed.html',
        {
            'save': save,
        },
    )

    trigger_client_event(
        response,
        'HotPocket:ViewAssociationView:loadEmbed',
        {},
        after='swap',
    )

    return response
