from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import F
from django.views.decorators.csrf import csrf_exempt

from .models import Movie, Person


def home(request):
    context = {}
    return render(request, 'home.html', context)


def movies(request, args=''):
    if args:
        try:
            id = int(args)
            return by_id(request, id)
        except ValueError:
            pass

    count = 0
    data = Movie.objects.to_dict(args.strip())
    directors = Person.objects.directors()
    if data:
        count = (len(data) - 1) * 4 + (len(data[-1]))
    context = {'movies': data, 'args': args, 'count': count,
        'directors': directors, 'selected_director': ''}
    return render(request, 'movies.html', context)


def by_id(request, id):
    count = 0
    data = Movie.objects.to_dict(id=id)
    directors = Person.objects.directors()
    if data:
        count = (len(data) - 1) * 4 + (len(data[-1]))
    context = {'movies': data, 'args': id, 'count': count,
        'directors': directors, 'selected_director': ''}
    return render(request, 'movies.html', context)


def by_director(request, name):
    data = Movie.objects.to_dict(director=name)
    directors = Person.objects.directors()
    count = (len(data) - 1) * 4 + (len(data[-1]))
    context = {'movies': data, 'args': 'by_director', 'count': count,
        'directors': directors, 'selected_director': name}
    return render(request, 'movies.html', context)


def addcount(request, id):
    response = ''
    if id:
        try:
            movie = Movie.objects.get(id=id)
            count = movie.count
            movie.count = F('count') + 1
            movie.save()
            response = count + 1
        except Movie.DoesNotExist:
            pass

    return HttpResponse(response)
