from django.urls import reverse_lazy
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa

from django.urls import reverse_lazy
from django.views.generic import CreateView, DetailView
from django.views.generic.list import ListView
from .models import Program, Exercise
from .forms import ExerciseForm

class ProgramListView(ListView):
    model = Program
    template_name = 'core/index.html'
    context_object_name = 'programs'

class ProgramCreateView(CreateView):
    model = Program
    template_name = 'core/program_form.html'
    fields = ['patient_name', 'patient_email', 'clinician_name']
    
    def get_success_url(self):
        return reverse_lazy('program_detail', kwargs={'pk': self.object.pk})

class ProgramDetailView(DetailView):
    model = Program
    template_name = 'core/program_detail.html'
    context_object_name = 'program'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['exercise_form'] = ExerciseForm()
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = ExerciseForm(request.POST)
        if form.is_valid():
            exercise = form.save(commit=False)
            exercise.program = self.object
            exercise.save()
            return self.render_to_response(self.get_context_data())
        return self.render_to_response(self.get_context_data(form=form))

class ProgramPDFView(View):
    def get(self, request, *args, **kwargs):
        program = Program.objects.get(pk=self.kwargs['pk'])
        template = get_template('core/program_pdf.html')
        context = {'program': program}
        html = template.render(context)
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="program_{program.pk}.pdf"'
        pisa_status = pisa.CreatePDF(html, dest=response)
        if pisa_status.err:
            return HttpResponse('We had some errors <pre>' + html + '</pre>')
        return response