import json
from datetime import datetime

from django.core.serializers import serialize, deserialize
from django.http import HttpResponse, HttpResponseNotAllowed, JsonResponse
from django.urls import reverse, reverse_lazy
from django.views.decorators.csrf import ensure_csrf_cookie

from articles.forms import AuthorForm
from articles.helpers.views import ListView, CreateView, UpdateView, DeleteView
from articles.models import Author, Article


class AuthorListView(ListView):
    template_name = 'authors/list.html'
    model = Author
    context_object_name = 'authors'
    ordering = ['name']
    paginate_by = 5


class AuthorCreateView(CreateView):
    template_name = 'authors/create.html'
    model = Author
    form_class = AuthorForm
    redirect_url = reverse_lazy('author_list')


class AuthorUpdateView(UpdateView):
    template_name = 'authors/update.html'
    model = Author
    form_class = AuthorForm
    redirect_url = reverse_lazy('author_list')


class AuthorDeleteView(DeleteView):
    model = Author
    confirm_deletion = False
    redirect_url = reverse_lazy('author_list')


@ensure_csrf_cookie
def get_token_view(request, *args, **kwargs):
    if request.method == 'GET':
        return HttpResponse()
    return HttpResponseNotAllowed('Разрешен только GET метод')


def json_echo_view(request, *args, **kwargs):
    answer = {
        'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'method': request.method
    }

    if request.body:
        answer['content'] = json.loads(request.body)

    answer_to_json = json.dumps(answer)
    response = HttpResponse(answer_to_json)
    response['Content-Type'] = 'application/json'

    return response


def article_api_list_view(request, *args, **kwargs):
    if request.method == 'GET':
        articles = Article.objects.all()
        articles_data = serialize('json', articles)
        print(articles_data)
        return HttpResponse(articles_data)


def article_api_create_view(request, *args, **kwargs):
    if request.method == 'POST':
        if request.body:
            article_data = deserialize('json', request.body)
            for item in article_data:
                item.save()

                return JsonResponse({'id': item.object.id})
        response = JsonResponse({'error': 'No data provided!'})
        response.status_code = 400
        return response
