from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
from django.views.decorators.http import require_http_methods
from django.conf import settings
from django.db import DatabaseError

from infoscreen.models import Rotation, InfoItem, InfoInstance

import json
import logging
import threading
import requests


@require_http_methods(["GET"])
def index(request, idx, *args, **kwargs):
    """Render infoscreen index page."""
    return render(request, 'infoscreen_index.html', {'rotation': idx})


@require_http_methods(["GET"])
def default(request, *args, **kwargs):
    """Try getting first rotation item."""
    try:
        first = Rotation.objects.all()[0].id
    except DatabaseError:
        first = 0
    return index(request, first, *args, **kwargs)


@require_http_methods(["GET"])
def get_apy_json(request):
    """Render APY diilikone page."""
    return HttpResponse(
        requests.get("https://api-diilikone.apy.fi/deals/top-groups").text)


@require_http_methods(["GET"])
def rotation(request, idx, *args, **kwargs):
    """Get rotation."""
    try:
        rotation = Rotation.objects.get(pk=idx)
    except Rotation.DoesNotExist:
        resp = HttpResponse('{"error": "Rotation not found"}')
        resp.status_code = 404
        return resp

    return HttpResponse(json.dumps(rotation.get_dict()))


@require_http_methods(["GET"])
def rotations(request, *args, **kwargs):
    """Return rotation lists."""
    rotations = list(map(lambda r: r.get_list(), Rotation.objects.all()))
    return HttpResponse(json.dumps(rotations))


@require_http_methods(["GET"])
def info_types(request, *args, **kwargs):
    """Return info item types."""
    types = []
    classes = InfoItem.get_subclasses()
    for c in classes:
        types.append({
            "name": c.display_name,
            "create_template_url": c.get_create_template_url(),
        })
    return HttpResponse(json.dumps(types))


@require_http_methods(["GET"])
def info_items(request, *args, **kwargs):
    """Return Infoscreen items."""
    items = []
    classes = InfoItem.get_subclasses()
    for c in classes:
        for i in c.objects.all():
            items.append(i.get_dict())

    return JsonResponse(items, safe=False)
