from django.contrib.auth import logout
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.views import LoginView
from django.forms.models import model_to_dict
from django.http import JsonResponse, Http404
from django.shortcuts import render, redirect, reverse


from .model_util import get_sites_for_user, get_site_view_context

from .models import Measurement, Group

import logging

def login_view(_request):
    return LoginView.as_view()

def logout_view(request):
    logout(request)
    return redirect(reverse("login"))


# Create your views here.
def index(request):
    context = {}
    return render(request, "datavis/dashboard_home.html", context)

def guest_demo(request):
    """
    Loads safe public data and presents a read-only view into it
    TODO: Make this not a clone of site_view?
    """
    test_site_id = 29
    if request.method == "GET":
        params = request.GET

        selected_windrow_id = params.get("row", None)
        selected_temp_site_id = params.get("temp_site", None)

        context = get_site_view_context(test_site_id, selected_windrow_id, selected_temp_site_id)
        return render(request, "datavis/site_view.html", context)
    return None

@permission_required('datavis.view_sites', raise_exception=True)
def all_sites(request):
    if request.method == "GET":
        context = {
                "available_sites": get_sites_for_user(),
        }
        return render(request, "datavis/all_sites.html", context)

    return None

@permission_required('datavis.view_sites', raise_exception=True)
def site_view(request, site_id: int, windrow_id: int = None, temp_site_id: int = None):
    if request.method == "GET":
        params = request.GET

        # selected_windrow_id = params.get("row", None)
        # selected_temp_site_id = params.get("temp_site", None)

        context = get_site_view_context(site_id, windrow_id, temp_site_id)

        if context is None:
            logging.error("Failed to get site context")
            raise Http404("Unknown site")

        return render(request, "datavis/site_view.html", context)

    return None

@permission_required('datavis.view_sites', raise_exception=True)
def windrow_charts_view(request, site_id: int):
    if request.method == "GET":
        params = request.GET
        selected_temperature_sites = params.getlist("tsite", [])
        context = get_site_view_context(site_id, None, None)

        # Temporary
        context["selected_temperature_sites"] = [int(id) for id in selected_temperature_sites]
        context["no_temperature_sites_selected"] = len(selected_temperature_sites) == 0

        context["visualize_as"] = params.get("visualize_as", "chart") # "table" | "chart"
        context["temperature_unit"] = params.get("temperature_unit", "c") # "c" | "f"
        context["show_depth"] = params.get("show_depth", "all") # "18" | "36" | "all"
        context["show_average_temp"] =  params.get("show_average_temp", "true") == "true" # True | False
        context["show_ambient_humidity"] =  params.get("show_ambient_humidity", "true") == "true" # True | False
        context["show_ambient_temp"] =  params.get("show_ambient_temp", "true") == "true" # True | False
        context["show_motion_events"] =  params.get("show_motion_events", "true") == "true" # True | False
        # end temporary

        return render(request, "datavis/windrow_view.html", context)

    return None

@permission_required('datavis.view_sites', raise_exception=True)
def windrow_view(request, site_id: int, windrow_id: int):
    if request.method == "GET":
        params = request.GET
        selected_temperature_sites = params.getlist("tsite", [])
        context = get_site_view_context(site_id, windrow_id, None)

        # Temporary
        context["selected_temperature_sites"] = [int(id) for id in selected_temperature_sites]
        context["no_temperature_sites_selected"] = len(selected_temperature_sites) == 0

        context["visualize_as"] = params.get("visualize_as", "chart") # "table" | "chart"
        context["temperature_unit"] = params.get("temperature_unit", "c") # "c" | "f"
        context["show_depth"] = params.get("show_depth", "all") # "18" | "36" | "all"
        context["show_average_temp"] =  params.get("show_average_temp", "true") == "true" # True | False
        context["show_ambient_humidity"] =  params.get("show_ambient_humidity", "true") == "true" # True | False
        context["show_ambient_temp"] =  params.get("show_ambient_temp", "true") == "true" # True | False
        context["show_motion_events"] =  params.get("show_motion_events", "true") == "true" # True | False
        # end temporary

        return render(request, "datavis/windrow_view.html", context)

    return None

@permission_required('datavis.view_sites', raise_exception=True)
def temperature_site_view(request, site_id: int, windrow_id: int, temp_site_id: int):
    if request.method == "GET":
        context = get_site_view_context(site_id, windrow_id, temp_site_id)
        return render(request, "datavis/windrow_view.html", context)

    return None

def chart_test(request):
    return render(request, "datavis/sample_chart.html")

@permission_required('datavis.view_sites', raise_exception=True)
def api_test_data(request):
    measurements = Measurement.objects.all().select_related("source_node")

    result = {}
    for measurement in measurements:
        if measurement.source_node.friendly_name not in result:
            result[measurement.source_node.friendly_name] = []
        result[measurement.source_node.friendly_name].append(model_to_dict(measurement))

    return JsonResponse(result)
