from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from users.decorators import require_access_token
from django.http import JsonResponse
from users.models import User
from coffees.models import Coffee
import datetime


@require_http_methods(['GET'])
def index(request):
    return JsonResponse({'msg': 'Welcome to Coffy API'})

@csrf_exempt
@require_http_methods(['POST'])
@require_access_token
def create(request):
    # Drink new coffee
    coffee = Coffee(user=request.user)
    # Save coffee
    coffee.save()
    return JsonResponse({'msg': 'You drank a coffee successfully!'}, status=200)

@csrf_exempt
@require_http_methods(['GET'])
def detail(request, username):
    # Get date now
    now = datetime.datetime.now()
    try:
        print 'Username' + username
        # Get user
        user = User.objects.get(username=username)
        # Populate cups data
        data = {
            'cups': Coffee.objects.filter(user=user).count(),
            'cups_today': Coffee.objects.filter(user=user, created_at__day=now.day, created_at__month=now.month, created_at__year=now.year).count(),
            'cups_month': Coffee.objects.filter(user=user, created_at__month=now.month, created_at__year=now.year).count(),
            'cups_year': Coffee.objects.filter(user=user, created_at__year=now.year).count()
        }
        return JsonResponse(data, status=200)
    except (User.DoesNotExist):
        return JsonResponse({'err': 'This user doesn\'t exist'}, status=200)
