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

from .statements import *

nu = datetime.datetime.now()

from django_countries import countries

from rowers.braintreestuff import mocktest

class PaymentTest(TestCase):
    def setUp(self):

        #        settings.DEBUG = True

        p1 = PaidPlan(
            shortname='free',
            name='Basic',
            external_id='a',
            price=0,
            clubsize=0,
            paymentprocessor='braintree',
            paymenttype='single',
            )

        p1.save()

        p2 = PaidPlan(
            shortname='pro_recurring',
            name='Pro (recurring)',
            external_id='b',
            price=15,
            clubsize=0,
            paymentprocessor='braintree',
            paymenttype='single',
            )

        p2.save()

        p3 = PaidPlan(
            shortname='pro_single',
            name='Pro (single)',
            external_id='c',
            price=20,
            clubsize=0,
            paymentprocessor='braintree',
            paymenttype='single',
            )

        p3.save()

        self.c = Client()
        self.password = faker.word()

        #    def tearDown(self):
        #       settings.DEBUG = False

    @patch('rowers.views.braintreestuff.create_customer',side_effect=mock_create_customer)
    @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
    def test_billing_view(self,mocked_create_customer,mocked_gateway):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()
        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/billing/'

        response = self.c.get(url)
        self.assertEqual(response.status_code,200)

        plans = PaidPlan.objects.filter(price__gt=0).order_by('price')
        plan = plans[0]

        country = faker.country()
        countrycode = 'NL'
        for code, name in list(countries):
            if name.lower() == country.lower():
                countrycode = code

        form_data = {
            'street_address':faker.street_address(),
            'city':faker.city(),
            'postal_code':faker.postalcode(),
            'country':countrycode,
            'plan':plan.id,
            }

        form = RowerBillingAddressForm(form_data)
        self.assertTrue(form.is_valid())

        form = PlanSelectForm(form_data,paymentprocessor='braintree')
        self.assertTrue(form.is_valid())

        response = self.c.post(url,form_data,follow=True)
        self.assertEqual(response.status_code,200)

        expected_url = '/rowers/checkout/'+str(plan.id)+'/'

        self.assertRedirects(response,
                             expected_url = expected_url,
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
    def test_upgrade_view(self,mocked_gateway):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        r.country = 'NL'
        r.customer_id = 34
        r.subscription_id = 34
        r.save()
        u.set_password(self.password)
        u.save()

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/upgrade/'

        response = self.c.get(url)
        self.assertEqual(response.status_code,200)

        plans = PaidPlan.objects.filter(price__gt=0).order_by('price')
        plan = plans[0]

        country = faker.country()
        countrycode = 'NL'
        for code, name in list(countries):
            if name.lower() == country.lower():
                countrycode = code

        form_data = {
            'street_address':faker.street_address(),
            'city':faker.city(),
            'postal_code':faker.postalcode(),
            'country':countrycode,
            'plan':plan.id,
            }

        form = RowerBillingAddressForm(form_data)
        self.assertTrue(form.is_valid())

        form = PlanSelectForm(form_data,paymentprocessor='braintree')
        self.assertTrue(form.is_valid())

        response = self.c.post(url,form_data,follow=True)
        self.assertEqual(response.status_code,200)

        expected_url = '/rowers/upgradecheckout/'+str(plan.id)+'/'

        self.assertRedirects(response,
                             expected_url = expected_url,
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
    def test_down_view(self,mocked_gateway):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        r.country = 'NL'
        r.customer_id = 34
        r.subscription_id = 34
        r.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        r.paidplan = plan
        r.save()
        u.set_password(self.password)
        u.save()

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/downgrade/'

        response = self.c.get(url)
        self.assertEqual(response.status_code,200)

        country = faker.country()
        countrycode = 'NL'
        for code, name in list(countries):
            if name.lower() == country.lower():
                countrycode = code

        form_data = {
            'street_address':faker.street_address(),
            'city':faker.city(),
            'postal_code':faker.postalcode(),
            'country':countrycode,
            'plan':plans[0].id,
            }

        form = RowerBillingAddressForm(form_data)
        self.assertTrue(form.is_valid())

        form = PlanSelectForm(form_data,paymentprocessor='braintree')
        self.assertTrue(form.is_valid())

        response = self.c.post(url,form_data,follow=True)
        self.assertEqual(response.status_code,200)

        expected_url = '/rowers/downgradecheckout/'+str(plans[0].id)+'/'

        self.assertRedirects(response,
                             expected_url = expected_url,
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
    def test_planstop_view(self,mocked_gateway):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        r.country = 'NL'
        r.customer_id = 34
        r.subscription_id = 34
        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        r.paidplan = plan
        r.save()

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/me/cancelsubscriptions/'

        response = self.c.get(url)
        self.assertEqual(response.status_code,200)


    @patch('rowers.views.braintreestuff.gateway',side_effect=MockBraintreeGateway)
    def test_planstobasic_view(self,mocked_gateway):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        r.country = 'NL'
        r.customer_id = 34
        r.subscription_id = 34
        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        r.paidplan = plan
        r.save()

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/me/cancelsubscription/34/'

        response = self.c.get(url,follow=True)
        self.assertEqual(response.status_code,200)
        self.assertRedirects(response,
                             expected_url = '/rowers/me/cancelsubscriptions/',
                             status_code=302,target_status_code=200)

    @patch('rowers.tests.test_payments.mocktest', side_effect=mock_mocktest)
    def test_patch(self, mock_mocktest):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        u.set_password(self.password)
        u.save()
        r.save()
        result = mocktest(r)
        self.assertEqual(result,'121')

    @patch('rowers.views.braintreestuff.create_subscription', side_effect=mock_create_subscription)
    def test_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'tac':'tac',
            'paymenttype': 'CreditCard'
            }

        form = BillingForm(form_data)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/checkouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        self.assertRedirects(response,
                             expected_url = '/rowers/paymentcompleted/?amount=20.00',
                             status_code=302,target_status_code=200)


    @patch('rowers.views.braintreestuff.update_subscription', side_effect=mock_update_subscription)
    def test_upgrade_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'paymenttype': 'CreditCard',
            'tac':'tac',
            }

        form = BillingForm(form_data)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/upgradecheckouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        self.assertRedirects(response,
                             expected_url = '/rowers/paymentcompleted/?amount=20.00',
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.update_subscription', side_effect=mock_update_subscription)
    def test_downgrade_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'paymenttype': 'CreditCard',
            'tac':'tac',
            }

        form = BillingForm(form_data)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/downgradecheckouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        self.assertRedirects(response,
                             expected_url = '/rowers/downgradecompleted/',
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.create_subscription', side_effect=mock_create_subscription)
    def test_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'paymenttype': 'CreditCard',
            'tac':True,
            }

        form = BillingForm(form_data)
        if not form.is_valid():
            print(form.errors)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/checkouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        expected_url = '/rowers/paymentcompleted/?amount=20.00'

        self.assertRedirects(response,
                             expected_url = expected_url,
                             status_code=302,target_status_code=200)


    @patch('rowers.views.braintreestuff.update_subscription', side_effect=mock_update_subscription)
    def test_upgrade_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'paymenttype': 'CreditCard',
            'tac':True,
            }

        form = BillingForm(form_data)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/upgradecheckouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        self.assertRedirects(response,
                             expected_url = '/rowers/paymentcompleted/?amount=20.00',
                             status_code=302,target_status_code=200)

    @patch('rowers.views.braintreestuff.update_subscription', side_effect=mock_update_subscription)
    def test_downgrade_checkouts_view(self,mock_subscription):
        u = UserFactory()
        r = Rower.objects.create(user=u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach',
                                      paymentprocessor='braintree',
                                      street_address = faker.street_address(),
                                      city = faker.city(),
                                      postal_code = faker.postalcode(),
                                      country = faker.country(),
        )

        r.save()
        u.set_password(self.password)
        u.save()

        plans = PaidPlan.objects.all().order_by('price')
        plan = plans[1]

        form_data = {
            'amount':'15.00',
            'plan': plans[1].id,
            'payment_method_nonce': 'aap',
            'paymenttype': 'CreditCard',
            'tac':True,
            }

        form = BillingForm(form_data)
        self.assertTrue(form.is_valid())

        login = self.c.login(username=u.username, password=self.password)
        self.assertTrue(login)

        url = '/rowers/downgradecheckouts/'

        response = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code,200)

        self.assertRedirects(response,
                             expected_url = '/rowers/downgradecompleted/',
                             status_code=302,target_status_code=200)
