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

from rowers.views.statements import *


# Stroke data form to test API upload
@login_required()
def strokedataform(request,id=0):

    try:
        id=int(id)
    except ValueError:
        id = 0

    try:
        w = Workout.objects.get(id=id)
    except Workout.DoesNotExist:
        raise Http404("Workout doesn't exist")

    if request.method == 'GET':
        form = StrokeDataForm()
        return render(request, 'strokedata_form.html',
                      {
                          'form':form,
                          'teams':get_my_teams(request.user),
                          'id':id,
                          'workout':w,
                      })
    elif request.method == 'POST':
        form = StrokeDataForm()

    return render(request, 'strokedata_form.html',
                  {
                      'form':form,
                      'teams':get_my_teams(request.user),
                      'id':id,
                      'workout':w,
                  })

# Process the POSTed stroke data according to the API definition
# Return the GET stroke data according to the API definition
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer

@csrf_exempt
@login_required()
@api_view(['GET','POST'])
def strokedatajson(request,id):
    """
    POST: Add Stroke data to workout
    GET: Get stroke data of workout
    """
    row = get_object_or_404(Workout,pk=id)
    if row.user != request.user.rower:
        raise PermissionDenied("You have no access to this workout")

    try:
        id = int(id)
    except ValueError:
        return HttpResponse("Not a valid workout number",status=400)


    if request.method == 'GET':
        # currently only returns a subset.
        columns = ['spm','time','hr','pace','power','distance']
        datadf = dataprep.getsmallrowdata_db(columns,ids=[id])
        with open('media/apilog.log','a') as logfile:
            logfile.write(str(timezone.now())+": ")
            logfile.write(request.user.username+"(GET) \n")
        return JSONResponse(datadf)

    if request.method == 'POST':
        checkdata,r = dataprep.getrowdata_db(id=row.id)
        if not checkdata.empty:
            return HttpResponse("Duplicate Error",409)
        # strokedata = request.POST['strokedata']
        # checking/validating and cleaning
        try:
            strokedata = json.loads(request.POST['strokedata'])
        except:
            return HttpResponse("No JSON object could be decoded",400)

        df = pd.DataFrame(strokedata)
        df.index = df.index.astype(int)
        df.sort_index(inplace=True)
        # time, hr, pace, spm, power, drivelength, distance, drivespeed, dragfactor, strokerecoverytime, averagedriveforce, peakdriveforce, lapidx
        try:
            time = df['time']/1.e3
        except KeyError:
            return HttpResponse("There must be time values",status=400)
        aantal = len(time)
        pace = df['pace']/1.e3
        if len(pace) != aantal:
            return HttpResponse("Pace array has incorrect length",status=400)
        distance = df['distance']
        if len(distance) != aantal:
            return HttpResponse("Distance array has incorrect length",status=400)

        spm = df['spm']
        if len(spm) != aantal:
            return HttpResponse("SPM array has incorrect length",status=400)

        res = dataprep.testdata(time,distance,pace,spm)
        if not res:
            return HttpResponse("Data are not numerical",status=400)

        power = trydf(df,aantal,'power')
        drivelength = trydf(df,aantal,'drivelength')
        drivespeed = trydf(df,aantal,'drivespeed')
        dragfactor = trydf(df,aantal,'dragfactor')
        drivetime = trydf(df,aantal,'drivetime')
        strokerecoverytime = trydf(df,aantal,'strokerecoverytime')
        averagedriveforce = trydf(df,aantal,'averagedriveforce')
        peakdriveforce = trydf(df,aantal,'peakdriveforce')
        wash = trydf(df,aantal,'wash')
        catch = trydf(df,aantal,'catch')
        finish = trydf(df,aantal,'finish')
        peakforceangle = trydf(df,aantal,'peakforceangle')
        driveenergy = trydf(df,aantal,'driveenergy')
        slip = trydf(df,aantal,'slip')
        lapidx = trydf(df,aantal,'lapidx')
        hr = trydf(df,aantal,'hr')

        starttime = totimestamp(row.startdatetime)+time[0]
        unixtime = starttime+time

        with open('media/apilog.log','a') as logfile:
            logfile.write(str(starttime)+": ")
            logfile.write(request.user.username+"(POST) \r\n")

        data = pd.DataFrame({'TimeStamp (sec)':unixtime,
                             ' Horizontal (meters)': distance,
                             ' Cadence (stokes/min)':spm,
                             ' HRCur (bpm)':hr,
                             ' DragFactor':dragfactor,
                             ' Stroke500mPace (sec/500m)':pace,
                             ' Power (watts)':power,
                             ' DriveLength (meters)':drivelength,
                             ' DriveTime (ms)':drivetime,
                             ' StrokeRecoveryTime (ms)':strokerecoverytime,
                             ' AverageDriveForce (lbs)':averagedriveforce,
                             ' PeakDriveForce (lbs)':peakdriveforce,
                             ' lapIdx':lapidx,
                             ' ElapsedTime (sec)':time,
                             'catch':catch,
                             'slip':slip,
                             'finish':finish,
                             'wash':wash,
                             'driveenergy':driveenergy,
                             'peakforceangle':peakforceangle,
        })


        r = getrower(request.user)

        timestr = row.startdatetime.strftime("%Y%m%d-%H%M%S")
        csvfilename ='media/Import_'+timestr+'.csv'

        res =  data.to_csv(csvfilename+'.gz',index_label='index',
                           compression='gzip')
        row.csvfilename = csvfilename
        row.save()

        powerperc = 100*np.array([r.pw_ut2,
                                  r.pw_ut1,
                                  r.pw_at,
                                  r.pw_tr,r.pw_an])/r.ftp

        ftp = float(r.ftp)
        if row.workouttype in mytypes.otwtypes:
            ftp = ftp*(100.-r.otwslack)/100.

        rr = rrower(hrmax=r.max,hrut2=r.ut2,
                    hrut1=r.ut1,hrat=r.at,
                    hrtr=r.tr,hran=r.an,ftp=ftp,
                    powerperc=powerperc,powerzones=r.powerzones)
        rowdata = rdata(row.csvfilename,rower=rr).df

        datadf = dataprep.dataprep(rowdata,id=row.id,bands=True,barchart=True,otwpower=True,empower=True)
        # mangling

        #
        return HttpResponse(row.id,status=201)

    #Method not supported
    return HttpResponseNotAllowed("Method not supported")
