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

from .statements import *

import rowers.dataprep as dataprep
from rowingdata import rowingdata

nu = datetime.datetime.now()

from django.core.files import File
from django.utils.six import BytesIO

from PIL import Image
from io import StringIO

@override_settings(TESTING=True)
class ForceUnits(TestCase):
    def setUp(self):
        redis_connection.publish('tasks','KILL')
        self.c = Client()

        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.user_workouts = WorkoutFactory.create_batch(12, user=self.r)
        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

    def tearDown(self):
        dataprep.delete_strokedata(1)

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

        filename = 'rowers/tests/testdata/PainsledForce.csv'
        f = open(filename,'rb')
        file_data = {'file': f}
        form_data = {
        'title':'test',
        'workouttype':'rower',
        'boattype':'1x',
        'notes':'aap noot mies',
        'make_plot':False,
        'upload_to_c2':False,
        'plottype':'timeplot',
        'file': f,
        }

        form = DocumentsForm(form_data,file_data)
        response = self.c.post('/rowers/workout/upload/', form_data, follow=True)

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

        self.assertEqual(response.status_code, 200)

        f.close()

        w = Workout.objects.get(id=1)
        self.assertEqual(w.forceunit,'lbs')

        df = dataprep.getsmallrowdata_db(['averageforce'],ids=[13])
        average_N = int(df['averageforce'].mean())
        self.assertEqual(average_N,399)

        data = dataprep.read_df_sql(13)
        average_N = int(data['averageforce'].mean())
        self.assertEqual(average_N,398)

        df,row = dataprep.getrowdata_db(id=13)
        average_N = int(df['averageforce'].mean())
        self.assertEqual(average_N,398)

        df = dataprep.clean_df_stats(df,ignoreadvanced=False)
        average_N = int(df['averageforce'].mean())
        self.assertEqual(average_N,398)

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

        filename = 'rowers/tests/testdata/EmpowerSpeedCoachForce.csv'
        f = open(filename,'rb')
        file_data = {'file': f}
        form_data = {
        'title':'test',
        'workouttype':'rower',
        'boattype':'1x',
        'notes':'aap noot mies',
        'make_plot':False,
        'upload_to_c2':False,
        'plottype':'timeplot',
        'file': f,
        }

        form = DocumentsForm(form_data,file_data)
        response = self.c.post('/rowers/workout/upload/', form_data, follow=True)

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

        self.assertEqual(response.status_code, 200)

        f.close()

        w = Workout.objects.get(id=13)
        self.assertEqual(w.forceunit,'N')

        df = dataprep.getsmallrowdata_db(['averageforce'],ids=[13])
        average_N = int(df['averageforce'].mean())
        self.assertEqual(average_N,267)

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

        filename = 'rowers/tests/testdata/colinforce.csv'
        f = open(filename,'rb')
        file_data = {'file': f}
        form_data = {
        'title':'test',
        'workouttype':'rower',
        'boattype':'1x',
        'notes':'aap noot mies',
        'make_plot':False,
        'upload_to_c2':False,
        'plottype':'timeplot',
        'file': f,
        }

        form = DocumentsForm(form_data,file_data)
        response = self.c.post('/rowers/workout/upload/', form_data, follow=True)

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

        self.assertEqual(response.status_code, 200)

        f.close()

        w = Workout.objects.get(id=13)
        self.assertEqual(w.forceunit,'N')

        df = dataprep.getsmallrowdata_db(['averageforce'],ids=[13])
        average_N = int(df['averageforce'].mean())
        self.assertEqual(average_N,113)

@override_settings(TESTING=True)
class TestForceUnit(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(14, user=self.r)
        self.factory = RequestFactory()
        self.password = faker.word()
        self.u.set_password(self.password)
        self.u.save()

        result = get_random_file(filename='rowers/tests/testdata/PainsledForce.csv')
        self.csvfilename = result['filename']

        self.wpainsled = WorkoutFactory(user=self.r,
                                     csvfilename=result['filename'],
                                     starttime=result['starttime'],
                                     startdatetime=result['startdatetime'],
                                     duration=result['duration'],
                                     distance=result['totaldist'],
                                     workouttype = 'rower',
        )

    def tearDown(self):
        w = Workout.objects.filter(csvfilename=self.csvfilename)
        id = w[0].id
        dataprep.delete_strokedata(id)

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

        w = Workout.objects.filter(csvfilename=self.csvfilename)
        id = w[0].id
        row = rowingdata(csvfile=w[0].csvfilename)
        average_N = int(row.df[' AverageDriveForce (N)'].mean())
        self.assertEqual(average_N,398)


        df = dataprep.getsmallrowdata_db(['averageforce'],ids=[w[0].id],doclean=False,
                                         compute=False)
        try:
            average_N = int(df['averageforce'].mean())
            if average_N != 0:
                self.assertEqual(average_N,398)
        except KeyError:
            pass
