import datetime

from django.shortcuts import render
from django.utils.timezone import now, localtime
from rest_framework import authentication, permissions, status, viewsets
import rest_framework.generics
from rest_framework.response import Response
from rest_framework.views import APIView

import recipe.models
import recipe.serializers

class RecipeAPI(rest_framework.generics.RetrieveUpdateAPIView):

  # authentication_classes = (authentication.TokenAuthentication,
  #                           authentication.SessionAuthentication,
  #                           authentication.BasicAuthentication)
  # permission_classes = (permissions.IsAuthenticated,)
  queryset = recipe.models.Recipe.objects.all()
  serializer_class = recipe.serializers.RecipeSerializer


class RecipeListAPI(rest_framework.generics.ListAPIView,
                    rest_framework.generics.CreateAPIView):

  # authentication_classes = (authentication.TokenAuthentication,
  #                           authentication.SessionAuthentication,
  #                           authentication.BasicAuthentication)
  # permission_classes = (permissions.IsAuthenticated,)
  queryset = recipe.models.Recipe.objects.all()
  serializer_class = recipe.serializers.RecipeSerializer


class WeekRecipeListAPI(rest_framework.generics.ListAPIView,
                        rest_framework.generics.CreateAPIView):

  queryset = recipe.models.DailyRecipe.objects.all()
  serializer_class = recipe.serializers.WeekRecipeSerializer

  def post(self, request, *args, **kwargs):
    # Monday == 0 ... Sunday == 6
    today = localtime()
    recipes = []
    for x in range(0, 7-today.weekday()):
      daily_recipe, __ = recipe.models.DailyRecipe.objects.get_or_create(
        date=today + datetime.timedelta(days=x)
      )
      daily_recipe.generate_recipe()
      recipes.append(daily_recipe.recipes.values_list('id', flat=True))
    return Response({}, status=status.HTTP_201_CREATED, headers={})

  def get(self, request, *args, **kwargs):
    today = localtime()
    week_start = (today - datetime.timedelta(days=today.weekday())).date()
    week_end = week_start + datetime.timedelta(days=6)
    daily_recipes = recipe.models.DailyRecipe.objects.filter(
      date__gte=week_start,
      date__lte=week_end,
    ).order_by('date')
    data = [{}] * (7 - len(daily_recipes))

    for daily_recipe in daily_recipes:
      data.append(daily_recipe.serialize())

    return Response(data)


class DailyRecipeAPI(rest_framework.generics.RetrieveUpdateAPIView):

  queryset = recipe.models.DailyRecipe.objects.all()
  serializer_class = recipe.serializers.DailyRecipeSerializer

  def post(self, request, *args, **kwargs):
    daily_recipe = recipe.models.DailyRecipe.objects.get(id=kwargs['pk'])
    daily_recipe.generate_recipe()
    return Response({}, status=status.HTTP_201_CREATED, headers={})
