from django.shortcuts import render
from django.http import HttpResponse,HttpResponseBadRequest
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_http_methods
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import permission_required 
from django.utils import timezone

from infoscreen.models import Rotation, InfoItem, InfoInstance
from infoscreen.models import ABBInfoItem, ExternalImageInfoItem, ImageInfoItem, SossoInfoItem
from infoscreen.models import ImageUploadForm

from datetime import datetime, timedelta
import json

def index(request,idx, *args, **kwargs):
    return render(request, 'infoscreen_index.html',{'rotation':idx})

@permission_required('infoscreen.change_infoinstance', login_url='/login')
def admin(request, *args, **kwargs):
    return render(request,'infoscreen_admin.html',{})

def default(request,*args,**kwargs):
    try:
        first = Rotation.objects.all()[0].id
    except:
        first = 0
    return index(request,first ,*args, **kwargs)

@require_http_methods(["GET"])
def rotation(request, idx, *args, **kwargs):
    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()))


def itemCreator(model):
    @ensure_csrf_cookie
    @require_http_methods(["POST"])
    @permission_required('infoscreen.change_infoinstance', login_url='/login')
    def createItem(request,*args, **kwargs):
        try:
            data = json.loads(request.body.decode("utf-8"))
        except ValueError:
            return HttpResponseBadRequest('{"status":"failure","error":"invalid json supplied"}')
        try:
            model.create_from_dict(data)
            return HttpResponse('{"status":"success"}')
        except RuntimeError as e:
            return HttpResponseBadRequest('{"status":"failure","error":"{}"}'.format(str(e)))
    return createItem

def itemDeletor(model):
    @ensure_csrf_cookie
    @require_http_methods(["DELETE"])
    @permission_required('infoscreen.change_infoinstance', login_url='/login')
    def deleteItem(request,*args, **kwargs):
        idx = kwargs.pop("idx", 0)
        try:
            item = model.objects.get(pk=idx)
        except model.DoesNotExist:
            resp = HttpResponse('{"error":"object not found"}')
            resp.status_code = 404
            return resp
        try:
            item.delete()
            return HttpResponse('{"status":"success"}')
        except:
            resp = HttpResponse('{"error" : "could not delete item"}')
            resp.status_code = 500
            return resp
    return deleteItem

# due to model structure this is little complicated
@ensure_csrf_cookie
@permission_required('infoscreen.change_infoinstance', login_url='/login')
@require_http_methods(["DELETE"])
def deleteInfoItem(request,*args, **kwargs):
    type_id = kwargs.pop("type_id", 0)
    idx = kwargs.pop("idx", 0)
    if True:
        ct = ContentType.objects.get_for_id(type_id)
        item = ct.get_object_for_this_type(pk=idx)
    else:
        resp = HttpResponse('{"error":"object not found"}')
        resp.status_code = 404
        return resp
    try:
        item.delete()
        return HttpResponse('{"status":"success"}')
    except:
        resp = HttpResponse('{"error" : "could not delete item"}')
        resp.status_code = 500
        return resp

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

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

def infoItems(request, *args, **kwargs):
    items = []
    classes = InfoItem.get_subclasses()
    for c in classes:
        for i in c.objects.all():
            items.append(i.get_dict())
    return HttpResponse(json.dumps(items))

@require_http_methods(["POST"])
@ensure_csrf_cookie
@permission_required('infoscreen.change_infoinstance', login_url='/login')
def createImageItem(request, *args, **kwargs):
    form = ImageUploadForm(request.POST,request.FILES)
    if not form.is_valid():
        return HttpResponseBadRequest('{"status":"failure","error":"invalid data supplied"}')

    img = form.cleaned_data['image']
    name = form.cleaned_data['name']
    ImageInfoItem.objects.create(img=img, name=name)
    return HttpResponse('{"status":"success"}')

createInstance = itemCreator(InfoInstance)
deleteInstance = itemDeletor(InfoInstance)
createABBItem = itemCreator(ABBInfoItem)
createSossoItem = itemCreator(SossoInfoItem)
createExternalImageInfoItem = itemCreator(ExternalImageInfoItem)
