from django.utils import timezone
from rowers.models import Workout, PowerTimeFitnessMetric, Rower, PaidPlan
import datetime
from rowers.utils import myqueue
import django_rq
queue = django_rq.get_queue('default')
queuelow = django_rq.get_queue('low')
from rowers.tasks import handle_updatefitnessmetric,handle_sendemail_expired
from rowers.mytypes import otwtypes
from django.contrib import messages
from django.http import HttpResponse

def getrower(user):
    try:
        r = Rower.objects.get(user=user)
    except Rower.DoesNotExist:
        r = Rower(user=user)
        r.save()

    return r

def do_update(user,mode='rower',days=42):
    r = getrower(user)

    startdate = timezone.now()-datetime.timedelta(days=days)

    # test if not something already done
    now_date = timezone.now().strftime('%Y-%m-%d')
    ms = PowerTimeFitnessMetric.objects.filter(
        user=user,
        workoutmode=mode).order_by("-date")

    if len(ms) == 0:
        max_workout_id = 0
        last_update_date = '1972-01-01'
    else:
        max_workout_id = max([m.last_workout for m in ms])
        last_update_date = ms[0].date.strftime('%Y-%m-%d')

        #last_update_date = max([m.date.strftime('%Y-%m-%d') for m in ms])



    if mode == 'rower':
        workouts = Workout.objects.filter(
            user=r,
            workouttype__in=['rower','dynamic','slides'],
            startdatetime__gte=startdate)
    else:
        workouts = Workout.objects.filter(
            user=r,
            workouttype__in=otwtypes,
            startdatetime__gte=startdate)

    theids = [int(w.id) for w in workouts]
    try:
        max_id = max(theids)
    except ValueError:
        max_id = 0


    if last_update_date < now_date and max_workout_id < max_id:
        job = myqueue(queuelow,
                      handle_updatefitnessmetric,
                      user.id,mode,theids,
        )


    return 1


class PowerTimeFitnessMetricMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed before the view is called
        if request.user.is_authenticated:
            result = do_update(request.user,mode='rower')
            result = do_update(request.user,mode='water')

        response = self.get_response(request)

        return response

from django.shortcuts import redirect


allowed_paths = [
    '/rowers/me/delete',
    '/',
    '/logout',
    '/logout/',
    '/rowers/me/gdpr-optin/',
    '/rowers/me/gdpr-optin-confirm/',
    '/rowers/me/gdpr-optin',
    '/rowers/me/gdpr-optin-confirm'
    '/rowers/exportallworkouts/',
    '/rowers/exportallworkouts',
    '/rowers/survey/'
]

class SurveyMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated and request.path not in allowed_paths:
            r = getrower(request.user)
            nexturl = request.path
            if 'survey' in nexturl:
                nexturl = '/rowers/list-workouts'
            mustseesurvey = request.user.date_joined <= timezone.now()-datetime.timedelta(days=14) and not r.surveydone
            if mustseesurvey:
                return redirect(
                    '/rowers/survey/?next=%s' % nexturl
                )

        response = self.get_response(request)

        return response

class GDPRMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated and request.path not in allowed_paths:
            r = getrower(request.user)
            nexturl = request.path
            if 'optin' in nexturl:
                nexturl = '/rowers/list-workouts'
            if not r.gdproptin:
                return redirect(
                    '/rowers/me/gdpr-optin/?next=%s' % nexturl
                )

        response = self.get_response(request)

        return response

class RowerPlanMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated and request.user.rower.rowerplan not in ['basic','freecoach']:
            if request.user.rower.paymenttype == 'single':
                if request.user.rower.planexpires < timezone.now().date():
                    messg = 'Your paid plan has expired. We have reset you to a free basic plan.'
                    messages.error(request,messg)
                    r = getrower(request.user)
                    r.rowerplan = 'basic'
                    r.paymenttype = 'single'
                    basicplans = PaidPlan.objects.filter(shortname='basic',price=0,
                                                         paymentprocessor='braintree')
                    r.paidplan = basicplans[0]
                    r.save()
                    # remove from Free Coach groups

                    # send email
                    job = myqueue(queue,
                                  handle_sendemail_expired,
                                  r.user.email,
                                  r.user.first_name,
                                  r.user.last_name,
                                  str(r.planexpires))

        response = self.get_response(request)

        return response
