import logging
import yaml

from django.shortcuts import render, redirect , get_object_or_404
from .forms import OrganizationForm
from .models import Organization,Document,Risk, DocumentTemplate,DocumentRiskControl,Control
from backend.core.utils import get_top_risk
from django.urls import reverse
from backend.accounts.utils import send_confirmation_email
from django.contrib.admin.views.decorators import staff_member_required
from django.template import Template, Context


# @login_required
# def index(request):
#     return HttpResponse('<h1>Django</h1><p>Página simples.</p>')

logger = logging.getLogger(__name__)

# @login_required
def index(request):
    template_name = 'index.html'
    return render(request, template_name)


def signup(request):
    if request.method == 'POST':
        form = OrganizationForm(request.POST)
        if form.is_valid():
            form.save()
            send_confirmation_email(form.data['email'])

            return render(request, 'thankyou.html', {
                'email': form.data['email'],
                })
        else:
            logging.error(form.errors)
            return render(request, 'signup.html', {'form': form})
    else:
        form = OrganizationForm()

    return render(request, 'signup.html', {'form': form})


def thankyou(request):
    return render(request, 'thankyou.html')

@staff_member_required
def template_preview(request, name):
    template = get_object_or_404(DocumentTemplate, name=name)
    parsed_template = template.to_dict()
    return render(request, 'template_preview.html', {'template': parsed_template})


def document(request, document_id):
    document = get_object_or_404(Document, id=document_id)
    risks = (
        DocumentRiskControl.objects
        .filter(document=document)
        .values('risk', 'risk__risk_name')
        .distinct()
    )

    risks_with_controls = []

    for risk_entry in risks:
        risk = {
            'id': risk_entry['risk'],
            'name': risk_entry['risk__risk_name']
        }

        controls = (
            DocumentRiskControl.objects
            .filter(document=document, risk_id=risk['id'])
            .values('control', 'control__name', 'weight')
            .distinct()
        )

        risks_with_controls.append({
            'risk': risk,
            'controls': list(controls)
        })

    template_obj = get_object_or_404(DocumentTemplate, name="Default Template")
    template_content = template_obj.content 

    try:
        template_segments = yaml.safe_load(template_content)
    except yaml.YAMLError as e:
        return render(request, 'error.html', {'error_message': 'Error parsing template.'})
    context = {
        'document': document,
        'risks_with_controls': risks_with_controls
    }
    rendered_content = ""
    for segment in template_segments:
        content = segment['content']
        django_template = Template(content)  
        rendered_content += django_template.render(Context(context)) 

    return render(request, 'document.html', {'rendered_html': rendered_content})