from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rowers.views.statements import *

def paidplans_view(request):
    if not request.user.is_anonymous:
        r = request.user.rower
        if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
            messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')
    else:
        r = None



    return render(request,
                  'paidplans.html',
                  {'rower':r})

@login_required()
def billing_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    if payments.is_existing_customer(r):
        url = reverse(upgrade_view)
        return HttpResponseRedirect(url)

    if request.method == 'POST':
        billingaddressform = RowerBillingAddressForm(request.POST)
        planselectform = PlanSelectForm(request.POST,paymentprocessor='braintree')
        if billingaddressform.is_valid():
            cd = billingaddressform.cleaned_data
            for attr, value in cd.items():
                setattr(r, attr, value)
            r.save()

        if billingaddressform.is_valid():
            if planselectform.is_valid():
                plan = planselectform.cleaned_data['plan']
                try:
                    customer_id = braintreestuff.create_customer(r)
                except ProcessorCustomerError:
                    messages.error(request,"Something went wrong registering you as a customer.")
                    url = reverse(billing_view)
                    return HttpResponseRedirect(url)
                url = reverse(payment_confirm_view,
                              kwargs={
                                  'planid':plan.id
                              })
                return HttpResponseRedirect(url)


    else:
        billingaddressform = RowerBillingAddressForm(instance=r)
        planselectform = PlanSelectForm(paymentprocessor='braintree')

    return render(request,
                  'billing.html',
                  {'rower':r,
                   'billingaddressform':billingaddressform,
                   'planselectform':planselectform,
                   })

@login_required()
def upgrade_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    if r.subscription_id is None or r.subscription_id == '':
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    if request.method == 'POST':
        billingaddressform = RowerBillingAddressForm(request.POST)
        planselectform = PlanSelectForm(request.POST,paymentprocessor='braintree')
        if billingaddressform.is_valid():
            cd = billingaddressform.cleaned_data
            for attr, value in cd.items():
                setattr(r, attr, value)
            r.save()

        if planselectform.is_valid():
            plan = planselectform.cleaned_data['plan']
            if billingaddressform.is_valid():
                url = reverse(upgrade_confirm_view,
                              kwargs={
                                  'planid':plan.id
                              })
                return HttpResponseRedirect(url)

    else:
        billingaddressform = RowerBillingAddressForm(instance=r)
        planselectform = PlanSelectForm(paymentprocessor='braintree',
                                        rower=r)

    return render(request,
                  'upgrade.html',
                  {'rower':r,
                   'billingaddressform':billingaddressform,
                   'planselectform':planselectform,
                   })

@login_required()
def downgrade_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    if r.subscription_id is None or r.subscription_id == '':
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    if request.method == 'POST':
        billingaddressform = RowerBillingAddressForm(request.POST)
        planselectform = PlanSelectForm(request.POST,paymentprocessor='braintree')
        if billingaddressform.is_valid():
            cd = billingaddressform.cleaned_data
            for attr, value in cd.items():
                setattr(r, attr, value)
            r.save()

        if planselectform.is_valid():
            plan = planselectform.cleaned_data['plan']

            if plan.price > r.paidplan.price:
                nextview = upgrade_confirm_view
            elif plan.price == r.paidplan.price:
                messages.info(request,'You did not select a new plan')
                url = reverse(downgrade_view)
                return HttpResponseRedirect(url)
            else:
                nextview = downgrade_confirm_view

            if billingaddressform.is_valid():
                url = reverse(nextview,
                              kwargs={
                                  'planid':plan.id
                              })
                return HttpResponseRedirect(url)

    else:
        billingaddressform = RowerBillingAddressForm(instance=r)
        planselectform = PlanSelectForm(paymentprocessor='braintree',
                                        rower=r,includeall=True, initial={'plan':r.paidplan})

    return render(request,
                  'downgrade.html',
                  {'rower':r,
                   'billingaddressform':billingaddressform,
                   'planselectform':planselectform,
                   })

@login_required()
def plan_stop_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    subscriptions = []

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    if r.paidplan is not None and r.paidplan.paymentprocessor == 'braintree':
        try:
            subscriptions = braintreestuff.find_subscriptions(r)
        except ProcessorCustomerError:
            r.paymentprocessor = None
            r.save()



    return render(request,
                  'subscriptions_cancel.html',
                  {'rower':r,
                   'subscriptions':subscriptions
                   })

@login_required()
def plan_tobasic_view(request,id=0):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paidplan.paymentprocessor == 'braintree':
        success, themessages,errormessages = braintreestuff.cancel_subscription(r,id)
        for message in themessages:
            messages.info(request,message)

        for message in errormessages:
            messages.error(request,message)

    url = reverse(plan_stop_view)

    return HttpResponseRedirect(url)



@login_required()
def upgrade_confirm_view(request,planid = 0):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    try:
        plan = PaidPlan.objects.get(id=planid)
    except PaidPlan.DoesNotExist:
        messages.error(request,"Something went wrong. Please try again.")
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    client_token = braintreestuff.get_client_token(r)

    return render(request,
                  "upgradeconfirm.html",
                  {
                      'plan':plan,
                      'client_token':client_token,
                      'rower':r,
                  })

@login_required()
def downgrade_confirm_view(request,planid = 0):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    try:
        plan = PaidPlan.objects.get(id=planid)
    except PaidPlan.DoesNotExist:
        messages.error(request,"Something went wrong. Please try again.")
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    r = request.user.rower

    client_token = braintreestuff.get_client_token(r)

    return render(request,
                  "downgradeconfirm.html",
                  {
                      'plan':plan,
                      'client_token':client_token,
                      'rower':r,
                  })


@login_required()
def payment_confirm_view(request,planid = 0):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    try:
        plan = PaidPlan.objects.get(id=planid)
    except PaidPlan.DoesNotExist:
        messages.error(request,"Something went wrong. Please try again.")
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    client_token = braintreestuff.get_client_token(r)

    return render(request,
                  "paymentconfirm.html",
                  {
                      'plan':plan,
                      'client_token':client_token,
                      'rower':r,
                  })


@login_required()
def checkouts_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)


    r = request.user.rower

    if r.paymentprocessor != 'braintree' and r.paymenttype == 'recurring':
        messages.error(request,'Automated payment processing is currently only available through BrainTree (by PayPal). You are currently on a recurring payment plan with PayPal. Contact the site administrator at support@rowsandall.com before you proceed')

    if request.method != 'POST':
        url = reverse(paidplans_view)
        return HttpResponseRedirect(url)

    form = BillingForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        success,amount = braintreestuff.create_subscription(r,data)
        if success:
            messages.info(request,"Your payment has succeeded and your plan has been updated")
            url = "{baseurl}?amount={amount:.2f}".format(
                baseurl = reverse(payment_completed_view),
                amount = amount)
            return HttpResponseRedirect(url)
        else:
            messages.error(request,"There was a problem with your payment")
            url = reverse(billing_view)
            return HttpResponseRedirect(url)
    elif 'tac' not in request.POST:
        try:
            planid = int(request.POST['plan'])
            url = reverse('payment_confirm_view',kwargs={'planid':planid})
            messages.error(request,"You must review and acknowledge the terms and conditions")
            return HttpResponseRedirect(url)
        except IndexError:
            messages.error(request,"There was an error in the payment form")
            url = reverse('billing_view')
            return HttpResponseRedirect(url)
    else:
        messages.error(request,"There was an error in the payment form")
        url = reverse(billing_view)
        return HttpResponseRedirect(url)

    url = reverse(paidplans_view)
    return HttpResponseRedirect(url)

@login_required()
def upgrade_checkouts_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)


    r = request.user.rower

    if request.method != 'POST':
        url = reverse(paidplans_view)
        return HttpResponseRedirect(url)

    form = BillingForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        success,amount = braintreestuff.update_subscription(r,data)
        if success:
            messages.info(request,"Your payment has succeeded and your plan has been updated")
            url = "{baseurl}?amount={amount:.2f}".format(
                baseurl = reverse(payment_completed_view),
                amount = amount)
            return HttpResponseRedirect(url)
        else:
            messages.error(request,"There was a problem with your payment")
            url = reverse(upgrade_view)
            return HttpResponseRedirect(url)

    elif 'tac' not in request.POST:
        try:
            planid = int(request.POST['plan'])
            url = reverse('upgrade_confirm_view',kwargs={'planid':planid})
            messages.error(request,"You must review and acknowledge the terms and conditions")
            return HttpResponseRedirect(url)
        except IndexError:
            messages.error(request,"There was an error in the payment form")
            url = reverse('billing_view')
            return HttpResponseRedirect(url)
    else:
        messages.error(request,"There was an error in the payment form")
        url = reverse(upgrade_view)
        return HttpResponseRedirect(url)

    url = reverse(paidplans_view)
    return HttpResponseRedirect(url)

@login_required()
def downgrade_checkouts_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)


    r = request.user.rower

    if request.method != 'POST':
        url = reverse(paidplans_view)
        return HttpResponseRedirect(url)

    form = BillingForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        success = braintreestuff.update_subscription(r,data,method='down')
        if success:
            messages.info(request,"Your plan has been updated")
            url = reverse(downgrade_completed_view)
            return HttpResponseRedirect(url)
        else:
            messages.error(request,"There was a problem with your transaction")
            url = reverse(upgrade_view)
            return HttpResponseRedirect(url)
    elif 'tac' not in request.POST:
        try:
            planid = int(request.POST['plan'])
            url = reverse('downgrade_confirm_view',kwargs={'planid':planid})
            messages.error(request,"You must review and acknowledge the terms and conditions")
            return HttpResponseRedirect(url)
        except IndexError:
            messages.error(request,"There was an error in the payment form")
            url = reverse('billing_view')
            return HttpResponseRedirect(url)

    else:
        messages.error(request,"There was an error in the payment form")
        url = reverse(upgrade_view)
        return HttpResponseRedirect(url)

    url = reverse(paidplans_view)
    return HttpResponseRedirect(url)


@login_required()
def payment_completed_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    amount = request.GET.get('amount',0)


    r = request.user.rower

    return render(request,
                  "payment_completed.html",
                  {
                      'rower':r,
                      'amount':amount,
                      })

@login_required()
def downgrade_completed_view(request):
    if not PAYMENT_PROCESSING_ON:
        url = reverse('promembership')
        return HttpResponseRedirect(url)

    r = request.user.rower

    return render(request,
                  "downgrade_completed.html",
                  {
                      'rower':r
                      })

# User registration
def rower_register_view(request):

    nextpage = request.GET.get('next','/rowers/list-workouts/')
    if nextpage == '':
        nextpage = '/rowers/list-workouts/'

    if request.method == 'POST':
        #form = RegistrationFormUniqueEmail(request.POST)
        form = RegistrationFormSex(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            username = form.cleaned_data['username']
            sex = form.cleaned_data['sex']
            birthdate = form.cleaned_data['birthdate']
            weightcategory = form.cleaned_data['weightcategory']
            adaptiveclass = form.cleaned_data['adaptiveclass']
            nextpage = request.POST['next']
            theuser = User.objects.create_user(username,password=password)
            theuser.first_name = first_name
            theuser.last_name = last_name
            theuser.email = email
            theuser.save()

            birthdate = birthdate.replace(tzinfo=None)

            therower = Rower(user=theuser,sex=sex,birthdate=birthdate,
                             weightcategory=weightcategory,
                             adaptiveclass=adaptiveclass)

            therower.save()

            # create default favorite charts
            add_defaultfavorites(therower)

            # Create Sample workout
            f = 'media/testdata.csv.gz'
            timestr = strftime("%Y%m%d-%H%M%S")
            f2 = f[:-7]+timestr+'.csv.gz'
            copyfile(f,f2)

            response = dataprep.new_workout_from_file(therower,f2,
                                                      title='New User Sample Data',
                                                      notes='This is an example workout to get you started')
            newworkoutid = response[0]
            if newworkoutid:
                w = Workout.objects.get(id=newworkoutid)
                w.startdatetime = timezone.now()
                w.date = timezone.now().date()
                w.save()

            # Create and send email
            fullemail = first_name + " " + last_name + " " + "<" + email + ">"
            subject = "Thank you for registering on rowsandall.com"
            from_address = 'Sander Roosendaal <info@rowsandall.com>'

            d = {'first_name':theuser.first_name}

            send_template_email(from_address,[fullemail],
                                subject,'registeremail.html',d)


            subject2 = "New User"
            message2 = "New user registered.\n"
            message2 += fullemail + "\n"
            message2 += "User name: "+username

            send_mail(subject2, message2,
                      'Rowsandall Server <info@rowsandall.com>',
                      ['roosendaalsander@gmail.com'])

            theuser = authenticate(username=username,password=password)
            login(request,theuser)

            return HttpResponseRedirect(nextpage)
        #        '/rowers/register/thankyou/')

        else:
            return render(request,
                          "registration_form.html",
                          {'form':form,
                           'next':nextpage,})
    else:
        form =  RegistrationFormSex()
        return render(request,
                      "registration_form.html",
                      {'form':form,
                       'next':nextpage,})

# User registration
def freecoach_register_view(request):

    nextpage = request.GET.get('next','/rowers/me/teams/')
    if nextpage == '':
        nextpage = '/rowers/me/teams/'

    if request.method == 'POST':
        #form = RegistrationFormUniqueEmail(request.POST)
        form = RegistrationFormSex(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            username = form.cleaned_data['username']
            sex = form.cleaned_data['sex']
            birthdate = form.cleaned_data['birthdate']
            weightcategory = form.cleaned_data['weightcategory']
            adaptiveclass = form.cleaned_data['adaptiveclass']
            nextpage = request.POST['next']
            theuser = User.objects.create_user(username,password=password)
            theuser.first_name = first_name
            theuser.last_name = last_name
            theuser.email = email
            theuser.save()

            birthdate = birthdate.replace(tzinfo=None)

            therower = Rower(user=theuser,sex=sex,birthdate=birthdate,
                             weightcategory=weightcategory,
                             adaptiveclass=adaptiveclass,
                             rowerplan='freecoach',clubsize=10)

            therower.save()

            # create default favorite charts
            add_defaultfavorites(therower)


            # Create and send email
            fullemail = first_name + " " + last_name + " " + "<" + email + ">"
            subject = "Thank you for registering on rowsandall.com"
            from_address = 'Sander Roosendaal <info@rowsandall.com>'

            d = {'first_name':theuser.first_name}

            send_template_email(from_address,[fullemail],
                                subject,'coachregisteremail.html',d)


            subject2 = "New Free Coach"
            message2 = "New Free Coach registered.\n"
            message2 += fullemail + "\n"
            message2 += "User name: "+username

            send_mail(subject2, message2,
                      'Rowsandall Server <info@rowsandall.com>',
                      ['roosendaalsander@gmail.com'])

            theuser = authenticate(username=username,password=password)
            login(request,theuser)

            return HttpResponseRedirect(nextpage)

        else:
            return render(request,
                          "freecoach_registration_form.html",
                          {'form':form,
                           'next':nextpage,})
    else:
        form =  RegistrationFormSex()
        form.fields.pop('sex')
        form.fields.pop('weightcategory')
        form.fields.pop('adaptiveclass')
        return render(request,
                      "freecoach_registration_form.html",
                      {'form':form,
                       'next':nextpage,})

@login_required()
@permission_required('rower.is_staff',fn=get_user_by_userid,raise_exception=True)
def transactions_view(request):
    if not request.user.is_staff:
        raise PermissionDenied("Not Allowed")

    if request.method == 'POST':
        dateform = DateRangeForm(request.POST)
        if dateform.is_valid():
            startdate = dateform.cleaned_data['startdate']
            enddate = dateform.cleaned_data['enddate']

            df = braintreestuff.get_transactions(startdate,enddate)
            filename="transactions_{s}_{e}.csv".format(s = startdate, e = enddate)
            response = HttpResponse(df.to_csv())
            response['Content-Disposition'] = 'attachment; filename="%s"' % filename
            response['Content-Type'] = 'application/octet-stream'

            return response

    else:
        dateform = DateRangeForm()

    return render(request,
                  'transactions.html',
                  {
                      'dateform':dateform
                  })
