from rowers.views.statements import *

# Export workout to TCX and send to user's email address
@permission_required('workout.change_workout',fn=get_workout_by_opaqueid,raise_exception=True)
def workout_tcxemail_view(request,id=0):
    r = getrower(request.user)
    w = get_workout(id)




    row = rdata(w.csvfilename)

    code = str(uuid4())
    tcxfilename = code+'.tcx'

    row.exporttotcx(tcxfilename)

    with open(tcxfilename,'r') as f:
        response = HttpResponse(f)
        response['Content-Disposition'] = 'attachment; filename="%s"' % tcxfilename
        response['Content-Type'] = 'application/octet-stream'

    os.remove(tcxfilename)
    return response





@login_required()
def plannedsessions_icsemail_view(request,userid=0):
    r = getrequestrower(request,userid=userid)
    startdate,enddate = get_dates_timeperiod(request)

    sps = get_sessions(r,startdate=startdate,enddate=enddate)

    cal = Calendar()
    cal.add('prodid','rowsandall')
    cal.add('version','1.0')

    for ps in sps:
        event = Event()
        comment = '{d} {u} {c}'.format(
            d=ps.sessionvalue,
            u = ps.sessionunit,
            c = ps.criterium)
        event.add('summary',ps.name)
        event.add('dtstart',ps.preferreddate)
        event.add('dtend',ps.preferreddate)
        event['uid'] = 'plannedsession_'+str(ps.id)
        event.add('description',ps.comment)
        event.add('comment',comment)
        cal.add_component(event)


    response = HttpResponse(cal.to_ical())
    response['Content-Disposition'] = 'attachment; filename="training_plan_{u}_{d1}_{d2}.ics"'.format(
        u =  request.user.username,
        d1 = startdate.strftime("%Y%m%d"),
        d2 = enddate.strftime("%Y%m%d"),
        )

    response['Content-Type'] = 'application/octet-stream'

    return response

@login_required()
def plannedsessions_coach_icsemail_view(request,userid=0):
    therower = getrequestplanrower(request,userid=userid)
    startdate,enddate = get_dates_timeperiod(request)

    if 'coach' in request.user.rower.rowerplan:
        sps = get_sessions_manager(request.user,teamid=0,
                                   enddate=enddate,
                                   startdate=startdate)
    else:
        rteams = therower.team.filter(viewing='allmembers')
        sps = get_sessions(therower,startdate=startdate,enddate=enddate)

    if therower.rowerplan != 'freecoach':
        rowers = [therower]
    else:
        rowers = []

    for ps in sps:
        if 'coach' in request.user.rower.rowerplan:
            rowers += ps.rower.all().exclude(rowerplan='freecoach')
        else:
            rowers += ps.rower.filter(team__in=rteams).exclude(rowerplan='freecoach')

    rowers = list(set(rowers))

    cal = Calendar()
    cal.add('prodid','rowsandall')
    cal.add('version','1.0')

    for ps in sps:
        event = Event()
        comment = '{d} {u} {c}'.format(
            d=ps.sessionvalue,
            u = ps.sessionunit,
            c = ps.criterium)
        event.add('summary',ps.name)
        event.add('dtstart',ps.preferreddate)
        event.add('dtend',ps.preferreddate)
        event['uid'] = 'plannedsession_'+str(ps.id)
        event.add('description',ps.comment)
        event.add('comment',comment)
        cal.add_component(event)


    icalstring = cal.to_ical()
    fname = "media/training_plan_{d1}_{d2}".format(
        d1 = startdate.strftime("%Y%m%d"),
        d2 = enddate.strftime("%Y%m%d"),
        )

    url = reverse('plannedsessions_coach_view')+'?when={d1}/{d2}'.format(
        d1 = startdate.strftime("%Y-%m-%d"),
        d2 = enddate.strftime("%Y-%m-%d"),
        )

    for rower in rowers:
        fname2 = fname+"_{u}.ics".format(u=rower.id)
        with open(fname2,'wb') as fop:
            fop.write(icalstring)

            job = myqueue(queue,handle_sendemail_ical,
                          rower.user.first_name,
                          rower.user.last_name,
                          rower.user.email,
                          url,
                          fname2,debug=False)

    return HttpResponseRedirect(url)

@login_required()
def course_kmldownload_view(request,id=0):
    r = getrower(request.user)
    if r.emailbounced:
        message = "Please check your email address first. Email to this address bounced."
        messages.error(request,message)
        return HttpResponseRedirect(
            reverse('course_view',
                    kwargs = {
                        'id':str(id),
                        })
            )

    course = GeoCourse.objects.get(id=id)

    kmlstring = courses.coursetokml(course)

    kmlfilename = 'course_{id}.kml'.format(id=id)

    response = HttpResponse(kmlstring)
    response['Content-Disposition'] = 'attachment; filename="{filename}"'.format(filename=kmlfilename)
    response['Content-Type'] = 'application/octet-stream'

    return response



# Export workout to GPX and send to user's email address
@permission_required('workout.change_workout',fn=get_workout_by_opaqueid,raise_exception=True)
def workout_gpxemail_view(request,id=0):
    r = getrower(request.user)
    w = get_workout(id)




    row = rdata(w.csvfilename)

    code = str(uuid4())
    gpxfilename = code+'.gpx'

    row.exporttogpx(gpxfilename)

    with open(gpxfilename,'r') as f:
        response = HttpResponse(f)
        response['Content-Disposition'] = 'attachment; filename="%s"' % gpxfilename
        response['Content-Type'] = 'application/octet-stream'

    os.remove(gpxfilename)
    return response

# Get Workout summary CSV file
@login_required()
def workouts_summaries_email_view(request):
    r = getrower(request.user)
    if r.emailbounced:
        message = "Please check your email address first. Email to this address bounced."
        messages.error(request, message)
        return HttpResponseRedirect(
            reverse(r.defaultlandingpage,
		    kwargs = {
			'id':str(w.id),
		    })
        )

    if request.method == 'POST':
        form = DateRangeForm(request.POST)
        if form.is_valid():
            startdate = form.cleaned_data['startdate']
            enddate = form.cleaned_data['enddate']
            filename = 'rowsandall_workouts_{first}_{last}.csv'.format(
                first=startdate,
                last=enddate
                )
            df = dataprep.workout_summary_to_df(r,startdate=startdate,enddate=enddate)
            df.to_csv(filename,encoding='utf-8')
            res = myqueue(queuehigh,handle_sendemailsummary,
                          r.user.first_name,
                          r.user.last_name,
                          r.user.email,
                          filename,
                          emailbounced = r.emailbounced
            )
            messages.info(request,'The summary CSV file was sent to you per email')
    else:
        form = DateRangeForm()

    return render(request,"export_workouts.html",
                  {
                      'form':form
                      })


# Get Workout CSV file and send it to user's email address
@permission_required('workout.change_workout',fn=get_workout_by_opaqueid,raise_exception=True)
def workout_csvemail_view(request,id=0):
    r = getrower(request.user)

    w = get_workout(id)

    rowdata = rdata(w.csvfilename)
    code = str(uuid4())
    filename = code+'.csv'

    rowdate = rowdata.rowdatetime
    starttimeunix = arrow.get(rowdate).timestamp
    df = rowdata.df

    try:
        df[' ElapsedTime (sec)'] = df['TimeStamp (sec)']
        df['TimeStamp (sec)'] = df['TimeStamp (sec)'] + starttimeunix
    except KeyError:
	    pass

    response = HttpResponse(df.to_csv())
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    response['Content-Type'] = 'application/octet-stream'

    return response


# Get Workout CSV file and send it to user's email address
@login_required()
@permission_required('rower.is_staff',fn=get_user_by_userid,raise_exception=True)
def workout_csvtoadmin_view(request,id=0):
    message = ""
    r = getrower(request.user)
    w = get_workout(id)


    csvfile = w.csvfilename
    res = myqueue(queuehigh,
                  handle_sendemailcsv,
                  'Sander',
                  'Roosendaal',
                  'roosendaalsander@gmail.com',
                  csvfile)

    successmessage = "The CSV file was sent to the site admin per email"
    messages.info(request,successmessage)
    url = reverse('workout_view',
		  kwargs = {
		      'id':encoder.encode_hex(w.id),
		  })
    response = HttpResponseRedirect(url)

    return response
