# -*- encoding: utf-8 -*-

from datetime import timedelta, datetime

from django import template
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template import loader
from django.shortcuts import render
from django.urls import reverse
from django.forms.models import model_to_dict

from ..authentication.models import Department
from .models import Ticket, TicketPriority, TicketTag


@login_required()
def dashboard(request):
    return render(request, "home/dashboard.html")


@login_required()
def tickets(request):
    tickets = Ticket.objects.all().order_by("-create_timestamp")
    priorities = TicketPriority.objects.all()
    tags = TicketTag.objects.all()
    departments = Department.objects.all()

    context = {
        "tickets": tickets,
        "priorities": priorities,
        "tags": tags,
        "departments": departments,
        "dayago": datetime.now() - timedelta(hours=24)
    }

    return render(request, "home/tickets.html", context)


@login_required
@require_POST
def get_ticket(request):
    ticket = Ticket.objects.get(id=request.POST.get("ticket_id"))
    data = {"ticket": ticket.serialize()}
    return JsonResponse(data)


@login_required
@require_POST
def get_tickets(request, filters: dict):
    pass


@login_required()
def new_ticket(request):
    return render(request, "home/newticket.html")


@login_required()
def index(request):
    context = {'segment': 'index'}

    html_template = loader.get_template('home/index.html')
    return HttpResponse(html_template.render(context, request))


@login_required()
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

        load_template = request.path.split('/')[-1]

        if load_template == 'admin':
            return HttpResponseRedirect(reverse('admin:index'))
        context['segment'] = load_template

        html_template = loader.get_template('home/' + load_template)
        return HttpResponse(html_template.render(context, request))

    except template.TemplateDoesNotExist:

        html_template = loader.get_template('home/page-404.html')
        return HttpResponse(html_template.render(context, request))

    except:
        html_template = loader.get_template('home/page-500.html')
        return HttpResponse(html_template.render(context, request))
