from django.core.handlers.wsgi import WSGIRequest
from django.shortcuts import render
from django.views.generic import FormView, TemplateView
from django_weasyprint import WeasyTemplateView
from markdownx.utils import markdownify

from schickmacher.renderer.forms import RendererForm


def form_view(request: WSGIRequest):
    ctx = {"form": (RendererForm())}
    return render(request, 'renderer/render_form.html', ctx)


class HtmlRenderView(TemplateView):
    template_name = 'renderer/rendered.html'

    def get_context_data(self, **kwargs):
        form = RendererForm(self.request.POST)
        if form.is_valid():
            return {
                'date': form.cleaned_data['date'],
                'content': markdownify(form.cleaned_data['render_content']),
                'title': form.cleaned_data['title']
            }
        else:
            return {
                'date': 'Error',
                'content': 'Error',
                'title': 'Error'
            }

    def post(self, request, *args, **kwargs):
        return self.get(request, *args, **kwargs)


class RenderView(HtmlRenderView, WeasyTemplateView):
    pass
