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 rowers.views import *


class WorkoutCompareTest(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_compare(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/team-compare-select/workout/'+encoded1+'/team/0/user/1/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_compare_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        form_data = {
            'chartform':'Compare',
            'plottype':'scatter',
            'teamid':0,
            'workouts':['1','2','3'],
            'xparam':'distance',
            'yparam':'hr',
            }

        form = WorkoutMultipleCompareForm(form_data)
        chartform = ChartParamChoiceForm(form_data)
        self.assertTrue(form.is_valid())
        self.assertTrue(chartform.is_valid())

        response = self.c.post('/rowers/multi-compare/',form_data)

        self.assertEqual(response.status_code,200)


class BoxPlotTest(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_boxplot(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-boxplot-select/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    @patch('rowers.dataprep.read_cols_df_sql', side_effect = mocked_read_df_cols_sql_multi)
    def donot_test_workouts_boxplot_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db,
                                     mocked_df):

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

        form_data = {
            'workouts':['1','2','3'],
            'includereststrokes':False,
            'spmmax':55.0,
            'spmmin':15.0,
            'workmax':1500.0,
            'workmin':0.0,
            'yparam':'spm',
            }

        form = WorkoutMultipleCompareForm(form_data)
        chartform = BoxPlotChoiceForm(form_data)

        self.assertTrue(form.is_valid())
        self.assertTrue(chartform.is_valid())

        response = self.c.get('/rowers/user-boxplot/',follow=True)
        self.assertEqual(response.status_code,200)
        self.assertRedirects(response,
                             expected_url='/rowers/user-boxplot-select/user/1/',
                             status_code=302,target_status_code=200)

        response = self.c.post('/rowers/user-boxplot/',form_data)

        self.assertEqual(response.status_code,200)

        options = {}
        options['spmmin'] = 15
        options['spmmax'] = 55
        options['workmin'] = 0
        options['workmax'] = 5500
        options['ids'] = [1,2,3]
        options['userid'] = 1
        options['plotfield'] = 'spm'
        options['rankingonly'] = False

        session = self.c.session
        session['options'] = options
        session.save()
        response = self.c.get('/')

        sessionoptions = session['options']
        self.assertEqual(sessionoptions['ids'],[1,2,3])

        response = self.c.get('/rowers/user-boxplot-data/')


        self.assertEqual(response.status_code,200)


class ListWorkoutTest(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    @patch('rowers.dataprep.myqueue')
    def test_list_workouts(self, mocked_sqlalchemy,
                           mocked_getsmallrowdata_db,
                           mocked_myqueue):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'startdate':startdate,
            'enddate':enddate,
            }

        workouts = Workout.objects.filter(startdatetime__gte=startdate,
                                          startdatetime__lte=enddate)

        url = '/rowers/list-workouts/'

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


class PlannedSessionTests(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.user_sessions = SessionFactory.create_batch(
            5,
            manager=self.u)

        for session in self.user_sessions:
            session.rower.add(self.r)
            session.save()

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

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

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

        startdate, enddate = get_dates_timeperiod(response.wsgi_request)

        filename = 'training_plan_{u}_{d1}_{d2}.ics'.format(
            u = self.u.username,
            d1 = startdate.strftime("%Y%m%d"),
            d2 = enddate.strftime("%Y%m%d"),
        )
        self.assertEquals(
            response.get('Content-Disposition'),
            'attachment; filename="{name}"'.format(name=filename)
        )


class ForcecurveTest(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

    @patch('rowers.dataprep.getsmallrowdata_db',side_effect = mocked_getempowerdata_db)
    def test_forcecurve_plot(self, mocked_getsmallrowdata_db):
        login = self.c.login(username=self.u.username, password = self.password)
        self.assertTrue(login)

        encoded1 = str(encoder.encode_hex(1))
        url = '/rowers/workout/'+encoded1+'/forcecurve/'

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

class CumStatsTest(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

    @patch('rowers.dataprep.read_cols_df_sql', side_effect = mocked_read_df_cols_sql_multistats)
    def test_cumstats(self, mocked_df):
        login = self.c.login(username=self.u.username, password=self.password)
        self.assertTrue(login)

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

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

        self.assertEqual(response.status_code,200)

class CumFlexTest(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

    @patch('rowers.dataprep.read_cols_df_sql', side_effect = mocked_read_df_cols_sql_multiflex)
    def test_cumflex(self, mocked_df):
        login = self.c.login(username=self.u.username, password=self.password)
        self.assertTrue(login)

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        waterboattype = [u'1x',
                         u'2x',
                         u'2x+',
                         u'2-',
                         u'2+',
                         u'3x+',
                         u'3x-',
                         u'4x',
                         u'4x+',
                         u'4-',
                         u'4+',
                         u'8+',
                         u'8x+']

        form_data = {
            'startdate':startdate,
            'enddate':enddate,
            'modality':u'all',
            'waterboattype': waterboattype,
            'xaxis':'spm',
            'yaxis1':'driveenergy',
            'yaxis2':'power',
            }

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

        self.factory.user = self.u
        form = FlexAxesForm(self.factory,form_data)


        url = '/rowers/flexall/'

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

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


        options = {'enddatestring': '2019-01-14',
                   'includereststrokes': False,
                   'modality': u'water',
                   'rankingonly': False,
                   'startdatestring': '2018-12-15',
                   'theuser': 2,
                   'waterboattype': [u'1x',
                                     u'2x',
                                     u'2x+',
                                     u'2-',
                                     u'2+',
                                     u'3x+',
                                     u'3x-',
                                     u'4x',
                                     u'4x+',
                                     u'4-',
                                     u'4+',
                                     u'8+',
                                     u'8x+'],
                   'xparam': u'spm',
                   'yparam1': u'driveenergy',
                   'yparam2': u'power'}

        session = self.c.session
        session['options'] = options
        session.save()
        response = self.c.get('/')

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


class MultiFlexTest(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

    @patch('rowers.dataprep.read_cols_df_sql', side_effect = mocked_read_df_cols_sql_multiflex)
    def test_multiflex(self, mocked_df):
        login = self.c.login(username=self.u.username, password=self.password)
        self.assertTrue(login)

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        waterboattype = [u'1x',
                         u'2x',
                         u'2x+',
                         u'2-',
                         u'2+',
                         u'3x+',
                         u'3x-',
                         u'4x',
                         u'4x+',
                         u'4-',
                         u'4+',
                         u'8+',
                         u'8x+']

        form_data = {
            'startdate':startdate,
            'enddate':enddate,
            'modality':u'all',
            'waterboattype': waterboattype,
            'binsize':u'1',
            'palette':u'monochrome_blue',
            'spmmax':55,
            'spmmin':15,
            'workmax':1500,
            'workmin':0,
            'workouts':[1,2,3,4,5],
            'workoutselectform':'Create Chart',
            'xparam':'spm',
            'yparam':'power',
            'groupby':'driveenergy',
            }

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

        url = '/rowers/user-multiflex-select/'

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

        url = '/rowers/user-multiflex/user/1/'
        reponse = self.c.post(url, form_data,follow=True)
        self.assertEqual(response.status_code, 200)

        options={
            'includereststrokes':False,
            'ploterrorbars':True,
            'userid':0,
            'palette': 'monochrome_blue',
            'groupby': 'driveenergy',
            'binsize': 1,
            'xparam': 'spm',
            'yparam': 'power',
            'spmmin': 15,
            'spmmax': 55,
            'workmin': 400,
            'workmax': 1500,
            'ids': [1,2,3,4,5],
            'ploterrorbars':False,
        }

        session = self.c.session
        session['options'] = options
        session.save()
        response = self.c.get('/')

        url = '/rowers/user-multiflex-data/'
        response = self.c.get(url)
        self.assertEqual(response.status_code, 200)

class HistoTest(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getpowerdata_db)
    def test_histo_workouts(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        waterboattype = [u'1x',
                         u'2x',
                         u'2x+',
                         u'2-',
                         u'2+',
                         u'3x+',
                         u'3x-',
                         u'4x',
                         u'4x+',
                         u'4-',
                         u'4+',
                         u'8+',
                         u'8x+']

        form_data = {
            'startdate':startdate,
            'enddate':enddate,
            'modality':u'all',
            'waterboattype': waterboattype
            }

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

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


        options = {
            'includereststrokes':False,
            'rankingonly':False,
            'modality':'all',
            'waterboattype':waterboattype,
            'theuser':0,
            'enddatestring':enddate.strftime("%Y-%m-%d"),
            'startdatestring':startdate.strftime("%Y-%m-%d"),
        }

        session = self.c.session
        session['options'] = options
        session.save()
        response = self.c.get('/')

        sessionoptions = session['options']

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


        #--------------------------------------------------



class WorkoutCompareTestNew(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_compare(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-analysis-select/compare/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_compare_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'function':'compare',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'yaxis2':'hr',
            'groupby':'spm',
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'workouts':[1,2,3]
            }

        form = AnalysisChoiceForm(form_data)
        optionsform = AnalysisOptionsForm(form_data)
        dateform = DateRangeForm(form_data)

        result = form.is_valid()
        if not result:
            print(form.errors)

        self.assertTrue(form.is_valid())
        self.assertTrue(optionsform.is_valid())
        self.assertTrue(dateform.is_valid())

        response = self.c.post('/rowers/user-analysis-select/',form_data)

        self.assertEqual(response.status_code,200)

class WorkoutBoxPlotTestNew(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_boxplot(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-analysis-select/boxplot/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_boxplot_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'function':'boxplot',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'groupby':'spm',
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'workouts':[1,2,3]
            }

        form = AnalysisChoiceForm(form_data)
        optionsform = AnalysisOptionsForm(form_data)
        dateform = DateRangeForm(form_data)

        result = form.is_valid()
        if not result:
            print(form.errors)

        self.assertTrue(form.is_valid())
        self.assertTrue(optionsform.is_valid())
        self.assertTrue(dateform.is_valid())

        response = self.c.post('/rowers/user-analysis-select/',form_data)

        self.assertEqual(response.status_code,200)

class WorkoutHistoTestNew(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_histo(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-analysis-select/histo/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_histo_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'function':'histo',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'groupby':'spm',
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'workouts':[1,2,3]
            }

        form = AnalysisChoiceForm(form_data)
        optionsform = AnalysisOptionsForm(form_data)
        dateform = DateRangeForm(form_data)

        result = form.is_valid()
        if not result:
            print(form.errors)

        self.assertTrue(form.is_valid())
        self.assertTrue(optionsform.is_valid())
        self.assertTrue(dateform.is_valid())

        response = self.c.post('/rowers/user-analysis-select/',form_data)

        self.assertEqual(response.status_code,200)

class WorkoutFlexallTestNew(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_flexall(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-analysis-select/flexall/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_flexall_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'function':'flexall',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'groupby':'spm',
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'workouts':[1,2,3]
            }

        form = AnalysisChoiceForm(form_data)
        optionsform = AnalysisOptionsForm(form_data)
        dateform = DateRangeForm(form_data)

        result = form.is_valid()
        if not result:
            print(form.errors)

        self.assertTrue(form.is_valid())
        self.assertTrue(optionsform.is_valid())
        self.assertTrue(dateform.is_valid())

        response = self.c.post('/rowers/user-analysis-select/',form_data)

        self.assertEqual(response.status_code,200)

class WorkoutStatsTestNew(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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db')
    def test_workouts_stats(self, mocked_sqlalchemy,
                              mocked_getsmallrowdata_db):

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

        url = '/rowers/user-analysis-select/stats/'

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

    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    @patch('rowers.dataprep.read_cols_df_sql', side_effect=mocked_read_cols_df_sql)
    def test_analysis_data(self,
                           mocked_sqlalchemy,
                           mocked_getsmallrowdata_db,
                           mocked_read_cols_df_sql,
    ):

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        options = {
            'function':'flexall',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'groupby':'spm',
            'binsize':1,
            'ploterrorbars':True,
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'ids':[1,2,3],
            'userid':self.u.id,
            }

        workouts = self.user_workouts

        script, div = boxplotdata(workouts,options)
        script, div = trendflexdata(workouts,options)
#        script, div = histodata(workouts,options)
        script, div = flexalldata(workouts,options)
        script, div = statsdata(workouts,options)
        script, div = comparisondata(workouts,options)



    @patch('rowers.dataprep.create_engine')
    @patch('rowers.dataprep.getsmallrowdata_db', side_effect=mocked_getsmallrowdata_db)
    def test_workouts_stats_submit(self, mocked_sqlalchemy,
                                     mocked_getsmallrowdata_db):

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

        startdate = (self.user_workouts[0].startdatetime-datetime.timedelta(days=3)).date()
        enddate = (self.user_workouts[0].startdatetime+datetime.timedelta(days=3)).date()

        form_data = {
            'function':'stats',
            'xparam':'hr',
            'plotfield':'spm',
            'yparam':'pace',
            'groupby':'spm',
            'palette':'monochrome_blue',
            'xaxis':'time',
            'yaxis1':'power',
            'yaxis2':'hr',
            'startdate':startdate,
            'enddate':enddate,
            'plottype':'scatter',
            'spmmin':15,
            'spmmax':55,
            'workmin':0,
            'workmax':1500,
            'includereststrokes':False,
            'modality':'all',
            'waterboattype':['1x','2x','4x'],
            'rankingonly':False,
            'workouts':[1,2,3]
            }

        form = AnalysisChoiceForm(form_data)
        optionsform = AnalysisOptionsForm(form_data)
        dateform = DateRangeForm(form_data)

        result = form.is_valid()
        if not result:
            print(form.errors)

        self.assertTrue(form.is_valid())
        self.assertTrue(optionsform.is_valid())
        self.assertTrue(dateform.is_valid())

        response = self.c.post('/rowers/user-analysis-select/',form_data)

        self.assertEqual(response.status_code,200)
