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

#from __future__ import print_function
from .statements import *
nu = datetime.datetime.now()


import rowers

@pytest.mark.django_db
@override_settings(TESTING=True)
class C2Objects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )

        self.r.c2token = '12'
        self.r.c2refreshtoken = 'ab'
        self.r.tokenexpirydate = datetime.datetime.now()+datetime.timedelta(days=1)
        self.r.save()
        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )


    @patch('rowers.c2stuff.Session', side_effect=mocked_requests)
    def test_c2_callback(self, mock_Session):
        response = self.c.get('/call_back?code=dsdoij232s',follow=True)


        self.assertEqual(response.status_code, 200)


    @patch('rowers.c2stuff.Session', side_effect=mocked_requests)
    def test_c2_token_refresh(self, mock_Session):
        response = self.c.get('/rowers/me/c2refresh/',follow=True)

        self.assertEqual(response.status_code, 200)


    @patch('rowers.c2stuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.c2stuff.requests.get', side_effect=mocked_requests)
    def test_c2_upload(self, mock_get, mock_post):
        response = self.c.get('/rowers/workout/'+encoded1+'/c2uploadw/')

        self.assertRedirects(response,
                             expected_url = '/rowers/workout/'+encoded1+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.url, '/rowers/workout/'+encoded1+'/edit/')
        self.assertEqual(response.status_code, 302)

    @patch('rowers.c2stuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.c2stuff.requests.get', side_effect=mocked_requests)
    def test_c2_list(self, mock_get, mock_post):
        response = self.c.get('/rowers/workout/c2list',follow=True)

        self.assertEqual(response.status_code,200)

    @patch('rowers.c2stuff.requests.get', side_effect=mocked_requests)
    @patch('rowers.dataprep.create_engine')
    def test_c2_import(self, mock_get, mocked_sqlalchemy):

        response = self.c.get('/rowers/workout/c2import/12/',follow=True)

        self.assertRedirects(response,
                             expected_url='/rowers/workout/'+encoded2+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.status_code, 200)


    @patch('rowers.dataprep.create_engine')
    def test_strokedata(self, mocked_sqlalchemy):
        with open('rowers/tests/testdata/c2stroketestdata.txt','r') as infile:
            res = json.load(infile)

        strokedata = pd.DataFrame.from_dict(res['data'])

        with open('rowers/tests/testdata/c2testdata.txt','r') as infile:
            res = json.load(infile)

        data = res['data']

        from rowers.views import add_workout_from_strokedata

        res = add_workout_from_strokedata(self.u,1,data,strokedata,source='c2')

    @patch('rowers.dataprep.create_engine')
    def test_strokedatanohr(self, mocked_sqlalchemy):
        with open('rowers/tests/testdata/c2strokedatanohr.txt','r') as infile:
            res = json.load(infile)

        strokedata = pd.DataFrame.from_dict(res['data'])

        with open('rowers/tests/testdata/c2testdata.txt','r') as infile:
            res = json.load(infile)

        data = res['data']

        from rowers.views import add_workout_from_strokedata


        res = add_workout_from_strokedata(self.u,1,data,strokedata,source='c2')

@override_settings(TESTING=True)
class C2ObjectsTokenExpired(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )

        self.r.c2token = '12'
        self.r.c2refreshtoken = 'ab'
        self.r.tokenexpirydate = datetime.datetime.now()-datetime.timedelta(days=1)
        self.r.save()
        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )



    @patch('rowers.c2stuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.c2stuff.requests.get', side_effect=mocked_requests)
    @patch('rowers.c2stuff.Session',side_effect=mocked_requests)
    def test_c2_list(self, mock_get, mock_post, mock_Session):
        response = self.c.get('/rowers/workout/c2list',follow=True)

        self.assertEqual(response.status_code,200)

    @patch('rowers.c2stuff.requests.get', side_effect=mocked_requests)
    @patch('rowers.dataprep.create_engine')
    def test_c2_import(self, mock_get, mocked_sqlalchemy):

        response = self.c.get('/rowers/workout/c2import/12/',follow=True)

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

        self.assertEqual(response.status_code, 200)



#@pytest.mark.django_db
@override_settings(TESTING=True)
class StravaObjects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )

        self.r.stravatoken = '12'
        self.r.stravarefreshtoken = '123'
        self.r.stravatokenexpirydate = datetime.datetime.now()-datetime.timedelta(days=1)

        self.r.save()
        self.c.login(username='john',password='koeinsloot')
        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )


#    @patch('rowers.stravastuff.requests.post', side_effect=mocked_requests)
#    @patch('rowers.views.stravastuff.handle_stravaexport')
    #@patch('rowers.dataprep.getsmallrowdata_db')
    #def test_strava_upload(self, mock_post,MockStravalibClient,
    #                       mocked_getsmallrowdata_db):
 #   def test_strava_upload(self,mock_post, mocked_stravaexport):
 #       response = self.c.get('/rowers/workout/1/stravauploadw/')

  #      self.assertRedirects(response,
  #                           expected_url = '/rowers/workout/1/edit/',
  #                           status_code=302,target_status_code=200)

   #     self.assertEqual(response.url, '/rowers/workout/1/edit/')
   #     self.assertEqual(response.status_code, 302)

    @patch('rowers.stravastuff.requests.get', side_effect=mocked_requests)
    @patch('rowers.stravastuff.requests.post', side_effect=mocked_requests)
    def test_strava_list(self, mock_get, mockpost):
        result = rowers.stravastuff.rower_strava_token_refresh(self.u)
        self.assertEqual(result,"987654321234567898765432123456789")
        response = self.c.get('/rowers/workout/stravaimport/')

        self.assertEqual(response.status_code,200)

    @patch('rowers.utils.requests.get', side_effect=mocked_requests)
    @patch('rowers.stravastuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_strava_import(self, mock_get, mock_post,
                           mocked_getsmallrowdata_db):

        response = self.c.get('/rowers/workout/stravaimport/12',follow=True)

        self.assertRedirects(response,
                             expected_url='/rowers/workout/'+encoded2+'/edit/',
                             status_code=301,target_status_code=200)

        self.assertEqual(response.status_code, 200)

    @patch('rowers.stravastuff.requests.post', side_effect=mocked_requests)
    def test_strava_callback(self, mock_post):
        response = self.c.get('/stravacall_back?code=absdef23&scope=read',follow=True)
        self.assertEqual(response.status_code, 200)

    @patch('rowers.stravastuff.requests.post', side_effect=mocked_requests)
    def test_strava_token_refresh(self, mock_post):
        result = rowers.stravastuff.rower_strava_token_refresh(self.u)
        self.assertEqual(result,"987654321234567898765432123456789")



#@pytest.mark.django_db
@override_settings(TESTING=True)
class STObjects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )


        self.r.sporttrackstoken = '12'
        self.r.sporttracksrefreshtoken = '12'
        self.r.sporttrackstokenexpirydate = datetime.datetime.now()+datetime.timedelta(days=1)
        self.r.save()

        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )

    @patch('rowers.sporttracksstuff.requests.post', side_effect=mocked_requests)
    def test_sporttracks_callback(self, mock_post):
        response = self.c.get('/sporttracks_callback?code=dsdoij232s',follow=True)


        self.assertEqual(response.status_code, 200)


    @patch('rowers.sporttracksstuff.requests.post', side_effect=mocked_requests)
    def test_sporttracks_token_refresh(self, mock_post):
        response = self.c.get('/rowers/me/sporttracksrefresh/',follow=True)

        self.assertEqual(response.status_code, 200)


    @patch('rowers.sporttracksstuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.sporttracksstuff.requests.get', side_effect=mocked_requests)
    def test_sporttracks_upload(self, mock_get, mock_post):
        response = self.c.get('/rowers/workout/'+encoded1+'/sporttracksuploadw/')

        self.assertRedirects(response,
                             expected_url = '/rowers/workout/'+encoded1+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.url, '/rowers/workout/'+encoded1+'/edit/')
        self.assertEqual(response.status_code, 302)

    @patch('rowers.sporttracksstuff.requests.get', side_effect=mocked_requests)
    def test_sporttracks_list(self, mock_get):
        response = self.c.get('/rowers/workout/sporttracksimport',follow=True)

        self.assertEqual(response.status_code,200)

    @patch('rowers.imports.requests.get', side_effect=mocked_requests)
    def test_sporttracks_import(self, mock_get):

        response = self.c.get('/rowers/workout/sporttracksimport/12/',follow=True)

        self.assertRedirects(response,
                             expected_url='/rowers/workout/'+encoded2+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.status_code, 200)

    @patch('rowers.imports.requests.get', side_effect=mocked_requests)
    def test_sporttracks_import(self, mock_get):

        response = self.c.get('/rowers/workout/sporttracksimport/13/',follow=True)

        expected_url = reverse('workout_edit_view',
                               kwargs = {'id':encoder.encode_hex(2)})

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

        self.assertEqual(response.status_code, 200)

    @patch('rowers.imports.requests.get', side_effect=mocked_requests)
    def test_sporttracks_import_all(self, mock_get):

        response = self.c.get('/rowers/workout/sporttracksimport/all/',follow=True)

        expected_url = reverse('workouts_view')

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

        self.assertEqual(response.status_code, 200)

    @patch('rowers.dataprep.create_engine')
    def test_strokedata(self, mocked_sqlalchemy):
        with open('rowers/tests/testdata/sporttrackstestdata.txt','r') as infile:
            data = json.load(infile)

        from rowers.sporttracksstuff import add_workout_from_data

        res = add_workout_from_data(self.u,1,data,data)

    @patch('rowers.dataprep.create_engine')
    def test_strokedatanohr(self, mocked_sqlalchemy):
        with open('rowers/tests/testdata/sporttrackstestnohr.txt','r') as infile:
            data = json.load(infile)

        from rowers.sporttracksstuff import add_workout_from_data



        res = add_workout_from_data(self.u,1,data,data)

#@pytest.mark.django_db
@override_settings(TESTING=True)
class RunKeeperObjects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )


        self.r.runkeepertoken = '12'

        self.r.save()

        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )

    @patch('rowers.runkeeperstuff.requests.post', side_effect=mocked_requests)
    def test_runkeeper_callback(self, mock_post):
        response = self.c.get('/runkeeper_callback?code=dsdoij232s',follow=True)

        self.assertEqual(response.status_code, 200)

    @patch('rowers.runkeeperstuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.runkeeperstuff.requests.get', side_effect=mocked_requests)
    def test_runkeeper_upload(self, mock_get, mock_post):
        response = self.c.get('/rowers/workout/'+encoded1+'/runkeeperuploadw/')

        self.assertRedirects(response,
                             expected_url = '/rowers/workout/'+encoded1+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.url, '/rowers/workout/'+encoded1+'/edit/')
        self.assertEqual(response.status_code, 302)

    @patch('rowers.runkeeperstuff.requests.get', side_effect=mocked_requests)
    def test_runkeeper_list(self, mock_get):
        response = self.c.get('/rowers/workout/runkeeperimport',follow=True)

        self.assertEqual(response.status_code,200)

    @patch('rowers.imports.requests.get', side_effect=mocked_requests)
    def test_runkeeper_import(self, mock_get):

        response = self.c.get('/rowers/workout/runkeeperimport/12/',follow=True)

        self.assertRedirects(response,
                             expected_url='/rowers/workout/'+encoded2+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.status_code, 200)



@pytest.mark.django_db
@override_settings(TESTING=True)
class UAObjects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )


        self.r.underarmourtoken = '12'
        self.r.underarmourrefreshtoken = '12'
        self.r.underarmourtokenexpirydate = datetime.datetime.now()+datetime.timedelta(days=1)
        self.r.save()

        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )

    @patch('rowers.imports.requests.post', side_effect=mocked_requests)
    def test_underarmour_callback(self, mock_post):
        response = self.c.get('/underarmour_callback?code=dsdoij232s',follow=True)


        self.assertEqual(response.status_code, 200)


    @patch('rowers.underarmourstuff.requests.post', side_effect=mocked_requests)
    def test_underarmour_token_refresh(self, mock_post):
        response = self.c.get('/rowers/me/underarmourrefresh/',follow=True)

        self.assertEqual(response.status_code, 200)


    @patch('rowers.underarmourstuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.underarmourstuff.requests.get', side_effect=mocked_requests)
    def test_underarmour_upload(self, mock_get, mock_post):
        response = self.c.get('/rowers/workout/'+encoded1+'/underarmouruploadw/')

        self.assertRedirects(response,
                             expected_url = '/rowers/workout/'+encoded1+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.url, '/rowers/workout/'+encoded1+'/edit/')
        self.assertEqual(response.status_code, 302)

    @patch('rowers.underarmourstuff.requests.get', side_effect=mocked_requests)
    def test_underarmour_list(self, mock_get):
        response = self.c.get('/rowers/workout/underarmourimport',follow=True)

        self.assertEqual(response.status_code,200)

    @patch('rowers.imports.requests.get', side_effect=mocked_requests)
    @patch('rowers.dataprep.create_engine')
    def test_underarmour_import(self, mock_get, mocked_sqlalchemy):

        response = self.c.get('/rowers/workout/underarmourimport/12/',follow=True)

        self.assertRedirects(response,
                             expected_url='/rowers/workout/'+encoded2+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.status_code, 200)


#@pytest.mark.django_db
@override_settings(TESTING=True)
class TPObjects(DjangoTestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

        self.u.first_name = 'John'
        self.u.last_name = 'Sander'
        self.u.save()
        self.r = Rower.objects.create(user=self.u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )


        self.r.tptoken = '12'
        self.r.tprefreshtoken = '12'
        self.r.tptokenexpirydate = datetime.datetime.now()+datetime.timedelta(days=1)
        self.r.save()

        self.c.login(username='john',password='koeinsloot')

        self.nu = datetime.datetime.now()

        filename = 'rowers/tests/testdata/testdata.csv'

        rr = rrower(hrmax=self.r.max,hrut2=self.r.ut2,
                    hrut1=self.r.ut1,hrat=self.r.at,
                    hrtr=self.r.tr,hran=self.r.an,ftp=self.r.ftp)
        row = rdata(filename,rower=rr)
        totaldist = row.df['cum_dist'].max()
        totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()
        totaltime = totaltime+row.df.loc[:,' ElapsedTime (sec)'].iloc[0]


        hours = int(totaltime/3600.)
        minutes = int((totaltime - 3600.*hours)/60.)
        seconds = int(totaltime - 3600.*hours - 60.*minutes)
        tenths = int(10*(totaltime - 3600.*hours - 60.*minutes - seconds))

        duration = "%s:%s:%s.%s" % (hours,minutes,seconds,tenths)


        workoutdate = row.rowdatetime.strftime('%Y-%m-%d')
        workoutstarttime = row.rowdatetime.strftime('%H:%M:%S')

        self.w = Workout.objects.create(
            name='testworkout',workouttype='water',
            user=self.r,date=self.nu.strftime('%Y-%m-%d'),
            starttime=workoutstarttime,
            startdatetime=row.rowdatetime,
            duration=duration,distance=totaldist,
            csvfilename=filename
        )

    @patch('rowers.imports.requests.post', side_effect=mocked_requests)
    def test_tp_callback(self, mock_post):
        response = self.c.get('/tp_callback?code=dsdoij232s',follow=True)


        self.assertEqual(response.status_code, 200)


    @patch('rowers.tpstuff.requests.post', side_effect=mocked_requests)
    def test_tp_token_refresh(self, mock_post):
        response = self.c.get('/rowers/me/tprefresh/',follow=True)

        self.assertEqual(response.status_code, 200)


    @patch('rowers.tpstuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.tpstuff.requests.get', side_effect=mocked_requests)
    def test_tp_upload(self, mock_get, mock_post):
        url = '/rowers/workout/'+encoded1+'/tpuploadw/'

        response = self.c.get(url)

        self.assertRedirects(response,
                             expected_url = '/rowers/workout/'+encoded1+'/edit/',
                             status_code=302,target_status_code=200)

        self.assertEqual(response.url, '/rowers/workout/'+encoded1+'/edit/')
        self.assertEqual(response.status_code, 302)


#@pytest.mark.django_db
@override_settings(TESTING=True)
class AutoExportTests(TestCase):
    def setUp(self):
        redis_connection.publish('tasks','KILL')
        u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')
        r = Rower.objects.create(user=u,gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now()
        )

        r.c2_auto_export = True
        r.sporttracks_auto_export = True
        r.mapmyfitness_auto_export = True
        r.trainingpeaks_auto_export = True

        r.save()

        nu = datetime.datetime.now()
        workoutsbox = Mailbox.objects.create(name='workouts')
        workoutsbox.save()
        failbox = Mailbox.objects.create(name='Failed')
        failbox.save()

        filename = 'testdata.csv'

        m = Message(mailbox=workoutsbox,
                    from_header = u.email,
                    subject = filename,
                    body="""
---
workouttype: water
boattype: 2x
...
                    """)
        m.save()
        a2 = 'media/mailbox_attachments/'+filename
        copy('rowers/tests/testdata/'+filename,a2)
        a = MessageAttachment(message=m,document=a2[6:])
        a.save()

    def tearDown(self):
        for filename in os.listdir('media/mailbox_attachments'):
            path = os.path.join('media/mailbox_attachments/',filename)
            if not os.path.isdir(path):
                try:
                    os.remove(path)
                except (FileNotFoundError,OSError):
                    pass

    @patch('rowers.tpstuff.requests.post', side_effect=mocked_requests)
    @patch('rowers.tpstuff.requests.get', side_effect=mocked_requests)
    def test_emailprocessing(self, mock_post, mock_get):
        out = StringIO()
        call_command('processemail', stdout=out, testing=True)
        self.assertIn('Successfully processed email attachments',out.getvalue())
