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()

from rowingdata import rowingdata as rdata
from rowingdata import rower as rrower

from rowers.models import User,Rower, Workout

class UserMiddleWareTest(TestCase):
    def setUp(self):
        u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')
        self.r = Rower.objects.create(user=u)

        self.c = Client()
        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
        )


    def test_middleware(self):
        response = self.c.get('/rowers/list-workouts',follow=True)
        self.assertEqual(response.status_code,200)


class UserTestsNoRower(TestCase):
    def setUp(self):
        u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')

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


    def test_user(self):
        response = self.c.get('/rowers/list-workouts',follow=True)
        self.assertEqual(response.status_code,200)

class UserPreferencesTest(TestCase):
    def setUp(self):
        self.u = UserFactory()

        self.r = Rower.objects.create(user=self.u,
                                      birthdate=faker.profile()['birthdate'],
                                      gdproptin=True,surveydone=True,
                                      gdproptindate=timezone.now(),
                                      rowerplan='coach')

        self.c = Client()
        self.user_workouts = WorkoutFactory.create_batch(5, user=self.r)
        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

    def tearDown(self):
        for workout in self.user_workouts:
            try:
                os.remove(workout.csvfilename)
            except (IOError, OSError, FileNotFoundError):
                pass

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

        url = '/rowers/me/edit/'

        form_data = {
            'sex':'male',
            'birthdate':'1972-04-10',
            'weightcategory':'lwt',
            'adaptiveclass':'None',
            'getemailnotifications':True,
            'getimportantemails':True,
            'defaulttimezone':'UTC',
            'showfavoritechartnotes':False,
            'defaultlandingpage':'workout_edit_view',
            'first_name': self.u.first_name,
            'last_name': self.u.last_name,
            'email':self.u.email
            }

        form = AccountRowerForm(form_data)
        userform = UserForm(form_data,instance=self.u)
        self.assertTrue(form.is_valid())
        self.assertTrue(userform.is_valid())

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

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


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

        url = '/rowers/me/exportsettings/'
        response = self.c.get(url)
        self.assertEqual(response.status_code,200)

        form_data = {
            'stravaexportas':'Rowing',
            'polar_auto_import':True,
            'c2_auto_export':False,
            'c2_auto_import':False,
            'mapmyfitness_auto_export':False,
            'runkeeper_auto_export':False,
            'sporttracks_auto_export':False,
            'strava_auto_export':False,
            'strava_auto_import':False,
            'trainingpeaks_auto_export':False,
            }

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

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


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

        post_data = {
            u'middlepanel-0-panel':u'panel_middlesocial.html',
            u'middlepanel-1-panel':u'panel_statcharts.html',
            u'middlepanel-2-panel':u'flexthumbnails.html',
            u'middlepanel-3-panel':u'panel_summary.html',
            u'middlepanel-4-panel':u'panel_map.html',
            u'middlepanel-5-panel':u'panel_notes.html',
            u'middlepanel-6-panel':u'panel_shortcomment.html',
            u'middlepanel-7-panel':u'None',
            u'middlepanel-8-panel':u'None',
            u'middlepanel-INITIAL_FORMS':'8',
            u'middlepanel-MAX_NUM_FORMS':u'1000',
            u'middlepanel-MIN_NUM_FORMS':u'0',
            u'middlepanel-TOTAL_FORMS':u'8',
            }

        MiddlePanelFormSet = formset_factory(WorkFlowMiddlePanelElement,extra=1)
        middlepanel_formset = MiddlePanelFormSet(post_data,prefix='middlepanel')
        self.assertTrue(middlepanel_formset.is_valid())

        url = '/rowers/me/workflowconfig2/'
        response = self.c.get(url)

        self.assertEqual(response.status_code,200)

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

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

        form_data = {
            'max':181,
            'ut2':140,
            'ut1':150,
            'tr':170,
            'at':160,
            'an':175,
            'rest':50
            }

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

        url = '/rowers/me/preferences/'

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

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

        form_data = {
            'hrftp': 160,
            'ftp':230,
            'otwslack':14
            }

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

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


        form_data = {
            'pw_ut2':150,
            'pw_ut1':160,
            'pw_at':170,
            'pw_tr':200,
            'pw_an':230,
            'ut3name':'Recovery',
            'ut2name':'Pwr UT2',
            'ut1name':'Pwr UT1',
            'atname':'Pwr AT',
            'trname':'Pwr TR',
            'anname':'Explode'
            }

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