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

import json
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.contrib.auth import get_user_model
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator

from apps.api.serializers import TicketSerializer
from ..authentication.models import Department
from .models import Ticket, TicketPriority, TicketTag


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


class TicketView(TemplateView):
    template_name = "home/tickets.html"

    @method_decorator(login_required)
    def get(self, 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)

    # @method_decorator(login_required)
    # @require_POST
    # def fetch_ticket(self, request) -> JsonResponse:
    #     ticket = Ticket.objects.get(id=request.POST.get("ticket_id"))
    #     context = {"ticket": ticket.serialize()}
    #     return JsonResponse(context)

    # @method_decorator(login_required)
    # @require_POST
    # def fetch_tickets(self, request) -> JsonResponse:
    #     filters = json.loads(request.POST.get("filters", "{}"))
    #     queryset = Ticket.objects.all()

    #     for key, values in filters.items():
    #         print(key, values)
    
    #         for value in values:
    #             if value == "all": continue  # don't apply a filter if we want all
    #             queryset = queryset.filter(**{key: [value]})

    #     tickets = queryset.order_by("-create_timestamp")

    #     context = {"tickets": [ticket.serialize() for ticket in tickets]}

    #     return JsonResponse(context)

    # @method_decorator(login_required)
    # @require_POST
    # def fetch_filter_counts(self, request) -> JsonResponse:
    #     priorities = TicketPriority.objects.all()
    #     tags = TicketTag.objects.all()
    #     departments = Department.objects.all()

    #     tickets = Ticket.objects.all()

    #     context = {
    #         "priority_counts": {},
    #         "tag_counts": {},
    #         "department_counts": {},
    #         "ticket_count": tickets.count()
    #     }

    #     for priority in priorities:
    #         priority_count = tickets.filter(priority=priority).count()
    #         context["priority_counts"][str(priority.id)] = priority_count

    #     for tag in tags:
    #         tag_count = tickets.filter(tags__in=[tag]).count()
    #         context["tag_counts"][str(tag.id)] = tag_count

    #     for department in departments:
    #         department_count = tickets.filter(author__department=department).count()
    #         context["department_counts"][str(department.id)] = department_count

    #     return JsonResponse(context)

    # @method_decorator(login_required)
    # @require_POST
    # def new_ticket(self, request) -> JsonResponse:

    #     getall = lambda *keys: [request.POST.get(key) for key in keys]
    #     getlist = lambda key: request.POST.getlist(key)

    #     title, description, author_id, priority_id = getall(
    #         "title", "description", "author_id", "priority_id"
    #     )
    #     tag_ids = getlist("tag_ids[]")

    #     author = get_user_model().objects.get(id=author_id)
    #     priority = TicketPriority.objects.get(id=priority_id)
    #     tags = [
    #         tag for tag in TicketTag.objects.filter(id__in=tag_ids)
    #     ]

    #     ticket = Ticket.objects.create(
    #         title=title,
    #         description=description,
    #         author=author,
    #         priority=priority,
    #     )
    #     ticket.tags.set(tags)

    #     return JsonResponse({"success": "ticket created successfully"})


@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(uuid=request.POST.get("ticket_uuid"))
    serializer = TicketSerializer(ticket)
    data = {"ticket": serializer.data}
    return JsonResponse(data)


@login_required
@require_POST
def get_tickets(request):

    filters = json.loads(request.POST.get("filters", "{}"))
    queryset = Ticket.objects.all()

    for key, values in filters.items():
        print(key, values)
   
        for value in values:
            if value == "all": continue  # don't apply a filter if we want all
            queryset = queryset.filter(**{key: [value]})

    tickets = queryset.order_by("-create_timestamp")
    serializer = TicketSerializer(tickets, many=True)

    data = {"tickets": serializer.data}

    return JsonResponse(data)


@login_required
@require_POST
def get_filter_counts(request):

    priorities = TicketPriority.objects.all()
    tags = TicketTag.objects.all()
    departments = Department.objects.all()

    tickets = Ticket.objects.all()

    data = {
        "priority_counts": {},
        "tag_counts": {},
        "department_counts": {},
        "ticket_count": tickets.count()
    }

    for priority in priorities:
        data["priority_counts"][str(priority.uuid)] = tickets.filter(priority=priority).count()

    for tag in tags:
        data["tag_counts"][str(tag.uuid)] = tickets.filter(tags__in=[tag]).count()

    for department in departments:
        data["department_counts"][str(department.uuid)] = tickets.filter(author__department=department).count()

    return JsonResponse(data)

@login_required()
@require_POST
def new_ticket(request):
    print(request.POST)

    get = lambda key: request.POST.get(key)
    getlist = lambda key: request.POST.getlist(key)

    title = get("title")
    description = get("description")
    author_id = get("author_id")
    priority_id = get("priority_id")
    tag_ids = getlist("tag_ids[]")

    User = get_user_model()
    author = User.objects.get(id=author_id)

    priority = TicketPriority.objects.get(id=priority_id)
    tags = [
        tag for tag in TicketTag.objects.filter(id__in=tag_ids)
    ]

    ticket = Ticket.objects.create(
        title=title,
        description=description,
        author=author,
        priority=priority,
    )
    ticket.tags.set(tags)

    return JsonResponse({"success": "ticket created successfully"})


@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))
