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



#@pytest.mark.django_db
@override_settings(TESTING=True)
class PlotTests(TestCase):
    def setUp(self):
        redis_connection.publish('tasks','KILL')
        u = User.objects.create_user('john',
                                     'sander@ds.ds',
                                     'koeinsloot')
        r = Rower.objects.create(user=u,
                                 gdproptin=True,surveydone=True,
                                 gdproptindate=timezone.now(),
                                 rowerplan='basic')
        self.nu = datetime.datetime.now()
        filename = 'rowers/tests/testdata/testdata.csv'
        self.wotw = Workout.objects.create(name='testworkout',
                                        workouttype='water',
                                        user=r,date=self.nu.strftime('%Y-%m-%d'),
                                        starttime=self.nu.strftime('%H:%M:%S'),
                                        duration="0:55:00",distance=8000,
                                        csvfilename=filename)

        self.wote = Workout.objects.create(name='testworkout',
                                        workouttype='Indoor Rower',
                                        user=r,date=self.nu.strftime('%Y-%m-%d'),
                                        starttime=self.nu.strftime('%H:%M:%S'),
                                        duration="0:55:00",distance=8000,
                                        csvfilename=filename)

        #       timestr = strftime("%Y%m%d-%H%M%S")
        #       imagename = f1+timestr+'.png'
        #       fullpathimagename = 'static/plots/'+imagename
        powerperc = 100*np.array([r.pw_ut2,
                                  r.pw_ut1,
                                  r.pw_at,
                                  r.pw_tr,r.pw_an])/r.ftp


        self.hrdata = {
            'hrmax':r.max,
            'hrut2':r.ut2,
            'hrut1':r.ut1,
            'hrat':r.at,
            'hrtr':r.tr,
            'hran':r.an,
            'ftp':r.ftp,
            'powerperc':serialize_list(powerperc),
            'powerzones':serialize_list(r.powerzones),
        }

        self.c = Client()

    @patch('rowers.tasks.rdata')
    @patch('rowers.tasks.FigureCanvas')
    def test_ote_plots(self, mocked_rowingdata, mocked_canvas):
        w = self.wote
        f1 = 'testdata.csv'[:-4]
        timestr = strftime("%Y%m%d-%H%M%S")
        imagename = f1+timestr+'.png'
        fullpathimagename = 'static/plots/'+imagename
        # make plot - asynchronous task
        plotnr = 1
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 1
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 2
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 3
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 4
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 5
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 6
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 7
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 8
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 13
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

    @patch('rowers.tasks.rdata')
    @patch('rowers.tasks.FigureCanvas')
    def test_chartrequests(self, mocked_rowingdata, mocked_canvas):
        opid = encoder.encode_hex(self.wotw.id)

        url = reverse('workout_add_chart_view',
                      kwargs={'id':opid,
                              'plotnr':13
                              })

        workout_edit_url = reverse('workout_edit_view',
                                   kwargs={'id':opid})



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

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

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

        i = GraphImage.objects.filter(workout=self.wotw)
        self.assertEqual(len(i),1)

        graphid = i[0].id

        url = reverse('graph_delete',kwargs={'pk':graphid})

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

        response = self.c.post(url,{},follow=True)
        self.assertEqual(response.status_code,200)
        self.assertRedirects(response,
                             expected_url = workout_edit_url,
                             status_code=302,target_status_code=200)

        i = GraphImage.objects.filter(workout=self.wotw)
        self.assertEqual(len(i),0)



    @patch('rowers.tasks.rdata')
    @patch('rowers.tasks.FigureCanvas')
    def test_otw_plots(self, mocked_rowingdata, mocked_canvas):
        w = self.wotw
        f1 = 'testdata.csv'[:-4]
        timestr = strftime("%Y%m%d-%H%M%S")
        imagename = f1+timestr+'.png'
        fullpathimagename = 'static/plots/'+imagename
        # make plot - asynchronous task
        plotnr = 1
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 1
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 2
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 3
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 4
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 5
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 6
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 7
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 8
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 9
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass

        plotnr = 13
        if (w.workouttype=='water'):
            plotnr = plotnr+3

        res = handle_makeplot(f1,w.csvfilename,
                              w.name,self.hrdata,plotnr,imagename)
        i = GraphImage(workout=w,creationdatetime=self.nu,
                           filename=fullpathimagename)
        try:
            os.remove(fullpathimagename)
        except (FileNotFoundError,OSError):
            pass
