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 rowers.utils import allmonths,allsundays

import rowers.plannedsessions as plannedsessions

@override_settings(TESTING=True)
class TrainingPlanTest(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, FileNotFoundError,OSError):
                pass

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

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

        # add target

        targetdate = (nu+datetime.timedelta(days=300))

        form_data = {
            'name': faker.word(),
            'date': targetdate.strftime("%Y-%m-%d"),
            'notes': faker.text(),
            }

        targetform = TrainingTargetForm(form_data,user=self.u)
        self.assertTrue(targetform.is_valid())

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

        form_data = {
            'name': faker.word(),
            'target': '1',
            'startdate': nu.strftime("%Y-%m-%d"),
            'enddate': targetdate.strftime("%Y-%m-%d"),
            'active': True,
            }

        newplanform = TrainingPlanForm(form_data,user=self.u)
        self.assertTrue(newplanform.is_valid())

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

        urlplan = '/rowers/plan/1/'
        response = self.c.get(urlplan)
        self.assertEqual(response.status_code,200)

        html = BeautifulSoup(response.content,'html.parser')
        urls = [a['href'] for a in html.find_all('a')]

        for url in urls:
            if 'macrocycle' in url and 'delete' not in url:
                macrourl = url
                print(macrourl)
                response = self.c.get(macrourl)
                self.assertEqual(response.status_code,200)

                form_data = {
                    'name':faker.word(),
                    'startdate':nu.strftime("%Y-%m-%d"),
                    'enddate':targetdate.strftime("%Y-%m-%d"),
                    'notes':faker.text(),
                    }

                macroform = TrainingMacroCycleForm(form_data)
                self.assertTrue(macroform.is_valid())

                response = self.c.post(macrourl,form_data,follow=True)
                self.assertEqual(response.status_code,200)
                self.assertRedirects(response,
                                     expected_url='/rowers/plan/1/macro/3/',
                                     status_code=302,target_status_code=200)

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

        html = BeautifulSoup(response.content,'html.parser')
        urls = [a['href'] for a in html.find_all('a')]

        for url in urls:
            if 'planbymonths' in url:
                print(url)
                response = self.c.get(url,follow=True)
                self.assertEqual(response.status_code,200)

        response = self.c.get('/rowers/plan/1/macro/3/')
        self.assertEqual(response.status_code,200)

        html = BeautifulSoup(response.content,'html.parser')
        urls = [a['href'] for a in html.find_all('a')]

        tested = False

        for url in urls:
            if 'planbyweeks' in url and not tested:
                response = self.c.get(url,follow=True)
                self.assertEqual(response.status_code,200)
                tested = True

    # add test for creating new sessions
    def test_sessions_create(self):

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

        url = reverse('plannedsession_create_view')

        startdate = nu.date()
        enddate = (nu+datetime.timedelta(days=3)).date()
        preferreddate = startdate

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

        post_data = {
            'comment': faker.text(),
            'criterium': 'none',
            'enddate': enddate.strftime("%Y-%m-%d"),
            'preferreddate': preferreddate.strftime("%Y-%m-%d"),
            'startdate': startdate.strftime("%Y-%m-%d"),
            'sessionmode':'time',
            'sessiontype':'session',
            'sessionunit':'min',
            'sessionvalue': '60',
            'name': faker.word(),
            }

        print('posting to sessions/create')

        form = PlannedSessionForm(post_data)
        self.assertTrue(form.is_valid())

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



@override_settings(TESTING=True)
class SessionLinkTest(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()
        self.pss = []

        for w in self.user_workouts:
            startdatetime = w.startdatetime

            startdate = (startdatetime-datetime.timedelta(days=1)).date()
            enddate = (startdatetime+datetime.timedelta(days=1)).date()
            preferreddate = startdatetime.date()

            ps = SessionFactory(startdate=startdate,enddate=enddate,
                                sessiontype='session',
                                sessionmode = 'time',
                                criterium = 'none',
                                sessionvalue = 60,
                                sessionunit='min',
                                preferreddate=preferreddate,
                                manager=self.u,
                                )


            ps.save()

            self.pss.append(ps)

            result = plannedsessions.add_rower_session(self.r,ps)


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

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


        w = self.user_workouts[0]
        startdatetime = w.startdatetime

        startdate = (startdatetime-datetime.timedelta(days=1)).date()
        enddate = (startdatetime+datetime.timedelta(days=1)).date()

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

        post_data = {
            'startdate':startdate.strftime("%Y-%m-%d"),
            'enddate': enddate.strftime("%Y-%m-%d"),
        }

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

        url2 = '/rowers/sessions/manage/'
        response = self.c.get(url2,post_data)
        self.assertEqual(response.status_code,200)

        pss = PlannedSession.objects.filter(startdate=startdate,enddate=enddate)

        self.assertTrue(len(pss)>0)

        ps = pss[0]

        post_data = {
            'plannedsession': str(ps.id),
            'workouts':[str(w.id)],
            }

        plannedsessionstuple = []
        for ps in pss:
            sessiontpl = (ps.id,ps.__str__())
            plannedsessionstuple.append(sessiontpl)

        plannedsessionstuple = tuple(plannedsessionstuple)


        url2 += '?startdate={startdate}&enddate={enddate}'.format(
            startdate=startdate.strftime("%Y-%m-%d"),
            enddate = enddate.strftime("%Y-%m-%d"),
        )



        workoutdata = {}
        workoutdata['initial'] = []

        choices = []
        for w in self.user_workouts:
            wtpl = (w.id,w.__str__())
            choices.append(wtpl)

        workoutdata['choices'] = tuple(choices)

        form = PlannedSessionSelectForm(plannedsessionstuple,post_data)

        self.assertTrue(form.is_valid())

        form = WorkoutSessionSelectForm(workoutdata,post_data)
        self.assertTrue(form.is_valid())

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


        urlsession = '/rowers/sessions/{id}/'.format(id=ps.id)

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

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

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

        pss = PlannedSession.objects.all()

        earliestdate = min([ps.startdate for ps in pss])
        latestdate = max([ps.enddate for ps in pss])

        url = '/rowers/sessions/multicreate/?when={be}/{en}'.format(
            be = earliestdate.strftime("%Y-%m-%d"),
            en = latestdate.strftime("%Y-%m-%d"),
            )

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

        url = '/rowers/sessions/multicreate/user/{userid}/extra/1/?when={be}/{en}'.format(
            be = earliestdate.strftime("%Y-%m-%d"),
            en = latestdate.strftime("%Y-%m-%d"),
            userid = self.u.id
            )

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

        url = '/rowers/sessions/multiclone/user/{userid}/?when={be}/{en}'.format(
            be = earliestdate.strftime("%Y-%m-%d"),
            en = latestdate.strftime("%Y-%m-%d"),
            userid = self.u.id
            )

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

# 2019-01-13, rScore 69,

# 2019-01-12, HM

@override_settings(TESTING=True)
class SessionCompleteTest(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()

        # workout 1 - 2019-01-13, rScore 69
        result = get_random_file(filename='rowers/tests/testdata/2019-01-13_session.csv',name='sprintervals')


        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

        self.w1 = Workout.objects.create(
            name='sprintervals',
            notes=faker.text(),
            startdatetime = result['startdatetime'],
            starttime = result['starttime'],
            workouttype='rower',
            date=result['date'],
            duration=result['duration'],
            distance=result['totaldist'],
            csvfilename=result['filename'],
            trimp = 77,
            rscore = 69,
            hrtss = 43,
            normp = 236,
            user=self.r,
        )

        #        self.w1.save()

        startdatetime = self.w1.startdatetime

        startdate = (startdatetime-datetime.timedelta(days=1)).date()
        enddate = (startdatetime+datetime.timedelta(days=1)).date()
        preferreddate = startdatetime.date()

        self.ps_rscore = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='session',
            sessionmode = 'rScore',
            criterium = 'none',
            sessionvalue = 69,
            sessionunit='None',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_rscore.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_rscore)

        self.ps_dist = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='session',
            sessionmode = 'distance',
            criterium = 'none',
            sessionvalue = result['totaldist'],
            sessionunit='m',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_dist.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_dist)

        self.ps_time = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='session',
            sessionmode = 'time',
            criterium = 'none',
            sessionvalue = 38,
            sessionunit='min',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_time.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_time)

        self.ps_trimp = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='session',
            sessionmode = 'TRIMP',
            criterium = 'none',
            sessionvalue = 77,
            sessionunit='none',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_trimp.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_trimp)


    def tearDown(self):
        try:
            os.remove(self.w1.csvfilename)
        except (IOError, FileNotFoundError,OSError):
            pass

    def test_session1_complete(self):

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_rscore,self.r
        )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_rscore
        )

        self.assertEqual(verdict,'on target')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'on target')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'on target')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_trimp,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_trimp
        )

        self.assertEqual(verdict,'on target')

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


        url = reverse('plannedsession_comment_view',kwargs={'id':self.ps_rscore.id})

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

        form_data = {
            'comment': faker.text()
            }

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

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


    def test_session1_exact_complete(self):
        self.ps_rscore.criterium = 'exact'
        self.ps_rscore.save()

        self.ps_dist.criterium = 'exact'
        self.ps_dist.save()

        self.ps_time.criterium = 'exact'
        self.ps_time.save()

        self.ps_trimp.criterium = 'exact'
        self.ps_trimp.save()

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_rscore,self.r
        )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_rscore
        )

        self.assertEqual(verdict,'on target')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'on target')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.remove_workout_plannedsession(self.w1,self.ps_time)

        self.assertEqual(result,1)

        result = plannedsessions.remove_workout_plannedsession(self.w1,self.ps_time)

        self.assertEqual(result,0)

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_trimp,self.r
            )


        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_trimp
        )

        self.assertEqual(verdict,'on target')


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

        url = '/rowers/sessions/{id}/'.format(id=self.ps_trimp.id)

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

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


@override_settings(TESTING=True)
class ChallengeCompleteTest(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()

        # workout 1 - 2019-01-13, rScore 69
        result = get_random_file(filename='rowers/tests/testdata/2019-01-13_session.csv',name='sprintervals')


        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

        self.w1 = Workout.objects.create(
            name='sprintervals',
            notes=faker.text(),
            startdatetime = result['startdatetime'],
            starttime = result['starttime'],
            workouttype='rower',
            date=result['date'],
            duration=result['duration'],
            distance=result['totaldist'],
            csvfilename=result['filename'],
            trimp = 77,
            rscore = 69,
            hrtss = 43,
            normp = 236,
            user=self.r,
        )

        #        self.w1.save()

        startdatetime = self.w1.startdatetime

        startdate = (startdatetime-datetime.timedelta(days=1)).date()
        enddate = (startdatetime+datetime.timedelta(days=1)).date()
        preferreddate = startdatetime.date()

        self.ps_rscore = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='challenge',
            sessionmode = 'rScore',
            criterium = 'none',
            sessionvalue = 69,
            sessionunit='None',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_rscore.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_rscore)

        self.ps_dist = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='challenge',
            sessionmode = 'distance',
            criterium = 'none',
            sessionvalue = result['totaldist'],
            sessionunit='m',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_dist.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_dist)

        self.ps_time = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='challenge',
            sessionmode = 'time',
            criterium = 'none',
            sessionvalue = 38,
            sessionunit='min',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_time.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_time)

        self.ps_trimp = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='challenge',
            sessionmode = 'TRIMP',
            criterium = 'none',
            sessionvalue = 77,
            sessionunit='none',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_trimp.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_trimp)


    def tearDown(self):
        try:
            os.remove(self.w1.csvfilename)
        except (IOError, FileNotFoundError,OSError):
            pass

    def test_challenge1_complete(self):

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_rscore,self.r
        )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_rscore
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'partial')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_trimp,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_trimp
        )

        self.assertEqual(verdict,'partial')



    def test_challenge1_exact_complete(self):
        self.ps_rscore.criterium = 'exact'
        self.ps_rscore.save()

        self.ps_dist.criterium = 'exact'
        self.ps_dist.save()

        self.ps_time.criterium = 'exact'
        self.ps_time.save()

        self.ps_trimp.criterium = 'exact'
        self.ps_trimp.save()

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_rscore,self.r
        )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_rscore
        )

        self.assertEqual(verdict,'on target')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'on target')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.remove_workout_plannedsession(self.w1,self.ps_time)

        self.assertEqual(result,1)

        result = plannedsessions.remove_workout_plannedsession(self.w1,self.ps_time)

        self.assertEqual(result,0)


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

        url = '/rowers/sessions/{id}/'.format(id=self.ps_trimp.id)

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

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

@override_settings(TESTING=True)
class MandatoryTestCompleteTest(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()

        # workout 1 - 2019-01-13, rScore 69
        result = get_random_file(filename='rowers/tests/testdata/2019-01-13_session.csv',name='sprintervals')


        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

        self.w1 = Workout.objects.create(
            name='sprintervals',
            notes=faker.text(),
            startdatetime = result['startdatetime'],
            starttime = result['starttime'],
            workouttype='rower',
            date=result['date'],
            duration=result['duration'],
            distance=result['totaldist'],
            csvfilename=result['filename'],
            trimp = 77,
            rscore = 69,
            hrtss = 43,
            normp = 236,
            user=self.r,
        )

        #        self.w1.save()

        startdatetime = self.w1.startdatetime

        startdate = (startdatetime-datetime.timedelta(days=1)).date()
        enddate = (startdatetime+datetime.timedelta(days=1)).date()
        preferreddate = startdatetime.date()

        self.ps_rscore = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'rScore',
            criterium = 'none',
            sessionvalue = 69,
            sessionunit='None',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_rscore.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_rscore)

        self.ps_dist = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'distance',
            criterium = 'none',
            sessionvalue = result['totaldist'],
            sessionunit='m',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_dist.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_dist)

        self.ps_time = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'time',
            criterium = 'none',
            sessionvalue = 38,
            sessionunit='min',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_time.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_time)

        self.ps_trimp = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'TRIMP',
            criterium = 'none',
            sessionvalue = 77,
            sessionunit='none',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_trimp.save()
        added = plannedsessions.add_rower_session(self.r,self.ps_trimp)


    def tearDown(self):
        try:
            os.remove(self.w1.csvfilename)
        except (IOError, FileNotFoundError,OSError):
            pass

    def test_mandatorytest1_complete(self):

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_rscore,self.r
        )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_rscore
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'on target')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'partial')

        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_trimp,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_trimp
        )

        self.assertEqual(verdict,'partial')



    def test_mandatorytest1_exact_complete(self):
        self.ps_rscore.criterium = 'exact'
        self.ps_rscore.save()

        self.ps_dist.criterium = 'exact'
        self.ps_dist.save()

        self.ps_time.criterium = 'exact'
        self.ps_time.save()

        self.ps_trimp.criterium = 'exact'
        self.ps_trimp.save()


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_dist,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_dist
        )

        self.assertEqual(verdict,'on target')


        result = plannedsessions.add_workouts_plannedsession(
            [self.w1],self.ps_time,self.r
            )

        ratio,verdict,completiondate = plannedsessions.is_session_complete(
            self.r,self.ps_time
        )

        self.assertEqual(verdict,'partial')



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

        url = '/rowers/sessions/{id}/'.format(id=self.ps_time.id)

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

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

        url = reverse('plannedsession_compare_view',kwargs={'id':self.ps_dist.id})
        response = self.c.get(url,follow=True)
        self.assertEqual(response.status_code,200)

@override_settings(TESTING=True)
class PlannedSessionsView(TestCase):
    def setUp(self):
        # user
        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.r.save()
        self.c = Client()

        self.u2 = UserFactory(username='testbasicuser')
        self.r2 = Rower.objects.create(user=self.u2,
                                       birthdate=faker.profile()['birthdate'],
                                       gdproptin=True,surveydone=True,
                                       gdproptindate=timezone.now(),
                                       rowerplan='basic')

        self.password2 = faker.word()
        self.u2.set_password(self.password2)
        self.u2.save()

        self.team = Team.objects.create(
            name = faker.word(),
            notes = faker.text(),
            manager = self.u,
            )

        self.team.save()

        self.r.team.add(self.team)
        self.r2.team.add(self.team)
        self.r.save()
        self.r2.save()

        # workouts
        # workout 1 - 2019-01-13, rScore 69
        result = get_random_file(filename='rowers/tests/testdata/2019-01-13_session.csv',name='sprintervals')


        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

        self.w1 = Workout.objects.create(
            name='sprintervals',
            notes=faker.text(),
            startdatetime = result['startdatetime'],
            starttime = result['starttime'],
            workouttype='rower',
            date=result['date'],
            duration=result['duration'],
            distance=result['totaldist'],
            csvfilename=result['filename'],
            trimp = 77,
            rscore = 69,
            hrtss = 43,
            normp = 236,
            user=self.u.rower,
        )


        # plan
        self.target = TrainingTarget.objects.create(
            name = faker.word(),
            manager = self.u.rower,
            notes = faker.text()
        )
        self.target.rowers.add(self.u.rower)
        self.target.save()

        self.plan = TrainingPlan.objects.create(
            manager = self.u.rower,
            name = faker.word(),
            status=True,
            target = self.target,
            startdate=timezone.now().date(),
            enddate = self.target.date,
        )

        self.plan.rowers.add(self.u.rower)
        self.plan.save()

        # cycles
        self.macro = TrainingMacroCycle.objects.create(
            plan=self.plan,
            name=faker.word(),
            type='userdefined',
            notes = faker.text(),
            startdate = self.plan.startdate,
            enddate = self.plan.enddate,
        )

        mesos = TrainingMesoCycle.objects.filter(plan=self.macro)
        for m in mesos:
            m.delete()

        monthstarts = [d for d in allmonths(self.macro.startdate,self.macro.enddate)]
        monthstarts.append(self.macro.enddate)

        for i in range(len(monthstarts)-1):
            firstday = monthstarts[i]
            lastday = monthstarts[i+1]-datetime.timedelta(days=1)
            if lastday < self.macro.enddate and i == len(monthstarts)-2:
                lastday = self.macro.enddate

            meso = TrainingMesoCycle(startdate=firstday,
                                     enddate=lastday,
                                     plan=self.macro,
                                     name = '%s' % firstday.strftime("%B"),
                                     type = 'userdefined')
            meso.save()

        mesos = TrainingMesoCycle.objects.filter(plan=self.macro)

        for cycle in mesos:
            micros = TrainingMicroCycle.objects.filter(plan=cycle)
            for m in micros:
                m.delete()

            sundays = [s for s in allsundays(cycle.startdate,cycle.enddate)]

            if sundays and sundays[-1] < cycle.enddate:
                sundays = sundays+[cycle.enddate]
            elif not sundays:
                sundays = [cycle.enddate]

            for i in range(len(sundays)):
                if i==0:
                    monday = cycle.startdate
                else:
                    monday = sundays[i]-datetime.timedelta(days=6)
                    if monday < cycle.startdate:
                        monday = cycle.startdate

                nextsunday = sundays[i]

                micro = TrainingMicroCycle(startdate=monday,
                                           enddate=nextsunday,
                                           plan=cycle,
                                           name = 'Week %s' % monday.isocalendar()[1],
                                           type='userdefined')
                micro.save()


        # sessions
        startdatetime = self.w1.startdatetime

        startdate = (startdatetime-datetime.timedelta(days=1)).date()
        enddate = (startdatetime+datetime.timedelta(days=1)).date()
        preferreddate = startdatetime.date()

        self.startdate = startdate
        self.enddate = enddate

        self.ps_rscore = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'rScore',
            criterium = 'none',
            sessionvalue = 69,
            sessionunit='None',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_rscore.save()
        added = plannedsessions.add_rower_session(self.u.rower,self.ps_rscore)

        self.ps_dist = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'distance',
            criterium = 'none',
            sessionvalue = result['totaldist'],
            sessionunit='m',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_dist.save()
        added = plannedsessions.add_rower_session(self.u.rower,self.ps_dist)

        self.ps_time = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'time',
            criterium = 'none',
            sessionvalue = 38,
            sessionunit='min',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_time.save()
        added = plannedsessions.add_rower_session(self.u.rower,self.ps_time)

        self.ps_trimp = SessionFactory(
            startdate=startdate,enddate=enddate,
            sessiontype='test',
            sessionmode = 'TRIMP',
            criterium = 'none',
            sessionvalue = 77,
            sessionunit='none',
            preferreddate=preferreddate,
            manager=self.u,
        )


        self.ps_trimp.save()
        added = plannedsessions.add_rower_session(self.u.rower,self.ps_trimp)
        added = plannedsessions.add_team_session(self.team,self.ps_trimp)

    def tearDown(self):
        try:
            os.remove(self.w1.csvfilename)
        except (IOError, FileNotFoundError,OSError):
            pass

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

        url = '/rowers/sessions/{id}/clone/'.format(id=self.ps_trimp.id)
        today = datetime.date.today()
        b = datetime.date.today()-timezone.timedelta(today.weekday())
        e = b+timezone.timedelta(days=6)

        expected_url = '/rowers/sessions/teamedit/5/'

        response = self.c.get(url,follow=True)
        self.assertEqual(response.status_code,200)
        self.assertRedirects(response,
                             expected_url=expected_url,
                             status_code=302,target_status_code=200)

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

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

        formdata = {
            'startdate':self.startdate,
            'enddate':self.enddate,
            }

        form = DateRangeForm(formdata)
        self.assertTrue(form.is_valid())

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

        url = '/rowers/sessions/multiclone/?startdate={startdate}&enddate={enddate}'.format(
            startdate = self.startdate,
            enddate = self.enddate
            )

        formdata = {
            'plannedsessions':[self.ps_time.id,self.ps_trimp.id],
            'shiftstartdate':datetime.date.today()+timezone.timedelta(days=6)
            }

        form = PlannedSessionMultipleCloneForm(formdata)

        self.assertTrue(form.is_valid())

        form = SessionDateShiftForm(formdata)


        self.assertTrue(form.is_valid())

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


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

        # get something
        url = '/rowers/sessions/multicreate/user/1/extra/1/'
        response = self.c.get(url)
        self.assertEqual(response.status_code,200)

        data = {}

        data['csrf_token'] = response.context['csrf_token']

        management_form = response.context['ps_formset'].management_form
        for i in 'TOTAL_FORMS', 'INITIAL_FORMS', 'MIN_NUM_FORMS', 'MAX_NUM_FORMS':
            data['%s-%s' % (management_form.prefix,i)] = management_form[i].value()

        for i in range(response.context['ps_formset'].total_form_count()):
            current_form = response.context['ps_formset'].forms[i]

            for field_name in current_form.fields:
                value = current_form[field_name].value()
                data['%s-%s' % (current_form.prefix, field_name)] = value if value is not None else ''


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

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

        url = '/rowers/sessions/teamcreate/'
        response = self.c.get(url)

        self.assertEqual(response.status_code,200)

        form_data = {
            'team':[self.team.id],
            'startdate': self.w1.startdatetime.date(),
            'enddate': (self.w1.startdatetime+datetime.timedelta(days=5)).date(),
            'preferreddate': self.w1.startdatetime.date(),
            'name': faker.word(),
            'sessiontype': 'session',
            'sessionmode': 'distance',
            'criterium': 'none',
            'sessionvalue': 13000,
            'sessionunit': 'm',
            'course': '',
            'comment':faker.text()
            }

        plannedsessionform = PlannedSessionForm(form_data)

        self.assertTrue(plannedsessionform.is_valid())

        teamform = PlannedSessionTeamForm(self.u,form_data)

        self.assertTrue(teamform.is_valid())

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


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


        url = '/rowers/sessions/teamedit/{id}/'.format(id=self.ps_trimp.id)

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

        s = self.w1.startdatetime.date().strftime("%Y-%m-%d")
        e = (self.w1.startdatetime+datetime.timedelta(days=5)).date().strftime("%Y-%m-%d")
        p = self.w1.startdatetime.date().strftime("%Y-%m-%d")

        form_data = {
            'team':['1'],
            'startdate': s,
            'enddate': e,
            'preferreddate': p,
            'name': faker.word(),
            'sessiontype': 'session',
            'sessionmode': 'distance',
            'criterium': 'none',
            'sessionvalue': 13000,
            'sessionunit': 'm',
            'course': '',
            'comment':faker.text(),
            'members': ['{id1}'.format(id1=self.r.id)],
            'initial-startdate':s,
            'initial-enddate':e,
            'initial-preferreddate':p

            }


        form = PlannedSessionForm(form_data,instance=self.ps_trimp)
        if not form.is_valid():
            print(form.errors)
        self.assertTrue(form.is_valid())

        form = PlannedSessionTeamForm(self.u,form_data)
        if not form.is_valid():
            print(form.errors)
        self.assertTrue(form.is_valid())

        form = PlannedSessionTeamMemberForm(self.ps_trimp,form_data)
        if not form.is_valid():
            print(form.errors)
        self.assertTrue(form.is_valid())
        response = self.c.post(url,follow=True)
        self.assertEqual(response.status_code,200)


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

        d1 = (self.ps_trimp.startdate-datetime.timedelta(days=1)).strftime(
            "%Y-%m-%d")
        d2 = (self.ps_trimp.enddate+datetime.timedelta(days=1)).strftime(
            "%Y-%m-%d")

        sps = plannedsessions.get_sessions_manager(self.u,teamid=0,
                                   enddate=d2,startdate=d1)

        self.assertTrue(len(sps)>0)

        url = '/rowers/sessions/coach/?when={d1}/{d2}'.format(
            d1=d1,
            d2=d2,
            )

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


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

        url = '/rowers/sessions/?when={d1}/{d2}'.format(
            d1=self.ps_trimp.startdate.strftime("%Y-%m-%d"),
            d2=self.ps_trimp.enddate.strftime("%Y-%m-%d")
            )

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

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

        url = reverse('plannedsessions_view')

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

        d1 = self.ps_trimp.startdate
        d2 = self.ps_trimp.enddate

        dates = {
            'startdate': d1.strftime("%Y-%m-%d"),
            'enddate': d2.strftime("%Y-%m-%d")
            }

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

        dates = {
            'startdate': d1.strftime("%d-%m-%Y"),
            'enddate': d2.strftime("%d-%m-%Y"),
            }

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

        dates = {
            'startdate': d1.strftime("%d.%m.%Y"),
            'enddate': d2.strftime("%d.%m.%Y"),
            }

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

        dates = {
            'startdate': d1.strftime("%d/%m/%Y"),
            'enddate': d2.strftime("%d/%m/%Y"),
            }

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


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

        url = '/rowers/sessions/print/?when={d1}/{d2}'.format(
            d1=self.ps_trimp.startdate.strftime("%Y-%m%d"),
            d2=self.ps_trimp.enddate.strftime("%Y-%m%d")
            )

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

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

        url = '/rowers/sessions/manage/session/{id}/?when={d1}/{d2}'.format(
            d1=self.ps_trimp.startdate.strftime("%Y-%m%d"),
            d2=self.ps_trimp.enddate.strftime("%Y-%m%d"),
            id=self.ps_trimp.id,
            )

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

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

        url = '/rowers/sessions/{id}/edit/'.format(
            id=self.ps_time.id,
            )

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

        form_data = {
            'startdate': self.w1.startdatetime.date().strftime("%Y-%m-%d"),
            'enddate': (self.w1.startdatetime+datetime.timedelta(days=5)).date().strftime("%Y-%m-%d"),
            'preferreddate': self.w1.startdatetime.date().strftime("%Y-%m-%d"),
            'name': faker.word(),
            'sessiontype': 'session',
            'sessionmode': 'distance',
            'criterium': 'none',
            'sessionvalue': 13000,
            'sessionunit': 'm',
            'course': '',
            'comment':faker.text(),
            }

        form = PlannedSessionForm(form_data,instance=self.ps_time)
        if not form.is_valid():
            print(form.errors)

        self.assertTrue(form.is_valid())

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


    def test_plannedsession_detach_view(self):

        self.ps_time.startdate = self.w1.date-datetime.timedelta(days=3)
        self.ps_time.enddate = self.w1.date-datetime.timedelta(days=3)
        self.ps_time.save()

        self.w1.plannedsession = self.ps_time
        self.w1.save()

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

        url = '/rowers/sessions/{psid}/detach/{id}/'.format(
            psid=self.ps_time.id,
            id = encoder.encode_hex(self.w1.id),
            )

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

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

        url = '/rowers/sessions/{psid}/'.format(
            psid = self.ps_time.id
            )

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

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

        url = '/rowers/sessions/{psid}/delete/'.format(
            psid = self.ps_time.id
            )

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

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