# Processes emails sent to workouts@rowsandall.com
""" Processes emails sent to workouts@rowsandall.com """
import shutil
import time
from django.conf import settings
from rowers.tasks import (
    handle_sendemail_unrecognized,
    handle_sendemail_unrecognizedowner
    )
from django_mailbox.models import Message, MessageAttachment,Mailbox

workoutmailbox = Mailbox.objects.get(name='workouts')
failedmailbox = Mailbox.objects.get(name='Failed')


from rowers.models import User, Rower, RowerForm

from django.core.mail import EmailMessage

from rowingdata import rower as rrower

from rowingdata import rowingdata as rrdata

from rowingdata import get_file_type

import zipfile
import os
import rowers.dataprep as dataprep

import django_rq
queue = django_rq.get_queue('default')
queuelow = django_rq.get_queue('low')
queuehigh = django_rq.get_queue('default')

# Sends a confirmation with a link to the workout
from rowers.emails import send_template_email

def send_confirm(user, name, link, options):
    d = {
        'first_name':user.first_name,
        'name':name,
        'link':link,
        }

    fullemail = user.email
    subject = 'New Workout Added: '+name
    
    res = send_template_email('Rowsandall <info@rowsandall.com>',
                              [fullemail],
                              subject,'confirmemail.html',
                              d
                              )

    return 1

# Reads a "rowingdata" object, plus some error protections


def rdata(file, rower=rrower()):
    """ Reads rowingdata data or returns 0 on Error """
    try:
        result = rrdata(file, rower=rower)
    except IOError:
        try:
            result = rrdata(file + '.gz', rower=rower)
        except IOError:
            result = 0

    return result



def make_new_workout_from_email(rower, datafile, name, cntr=0,testing=False):
    """ This one is used in processemail """
    workouttype = 'rower'

    try:
        datafilename = datafile.name
        fileformat = get_file_type('media/' + datafilename)
    except IOError:
        datafilename = datafile.name + '.gz'
        fileformat = get_file_type('media/' + datafilename)
    except AttributeError:
        datafilename = datafile
        fileformat = get_file_type('media/' + datafile)

    if len(fileformat) == 3 and fileformat[0] == 'zip':
        with zipfile.ZipFile('media/' + datafilename) as zip_file:
            datafilename = zip_file.extract(
                zip_file.namelist()[0],
                path='media/')[6:]
            fileformat = fileformat[2]

    if testing:
        print 'Fileformat = ',fileformat
            
    if fileformat == 'unknown':
#        extension = datafilename[-4:].lower()
#        fcopy = "media/"+datafilename[:-4]+"_copy"+extension
#        with open('media/'+datafilename, 'r') as f_in, open(fcopy, 'w') as f_out:
#            shutil.copyfileobj(f_in,f_out)
        fcopy = "media/"+datafilename
        if not testing:
            if settings.DEBUG:
                res = handle_sendemail_unrecognized.delay(
                    fcopy,
                    rower.user.email
                )
                res = handle_sendemail_unrecognizedowner.delay(
                    rower.user.email,
                    rower.user.first_name
                )
            else:
                res = queuehigh.enqueue(handle_sendemail_unrecognized,
                                        fcopy,
                                        rower.user.email)
                res = queuehigh.enqueue(handle_sendemail_unrecognizedowner,
                                        rower.user.email,
                                        rower.user.first_name
                )
        return 0

    summary = ''

    
    # handle non-Painsled
    if fileformat != 'csv':
        filename_mediadir, summary, oarlength, inboard,fileformat = dataprep.handle_nonpainsled(
            'media/' + datafilename, fileformat, summary)
        if not filename_mediadir:
            return 0
    else:
        filename_mediadir = 'media/' + datafilename
        inboard = 0.88
        oarlength = 2.89

    row = rdata(filename_mediadir)  
    if row == 0:
        return 0

    # change filename
    if datafilename[:5] != 'media':
        timestr = time.strftime("%Y%m%d-%H%M%S")
        datafilename = 'media/' + timestr + str(cntr) + 'o.csv'

    try:
        avglat = row.df[' latitude'].mean()
        avglon = row.df[' longitude'].mean()
        if avglat != 0 or avglon != 0:
            workouttype = 'water'
    except KeyError:
        pass

    
    row.write_csv(datafilename, gzip=True)
    dosummary = (fileformat != 'fit' and 'speedcoach2' not in fileformat)
    dosummary = dosummary or summary == ''
    
    if name == '':
        name = 'Workout from Background Queue'

    id, message = dataprep.save_workout_database(
        datafilename, rower,
        workouttype=workouttype,
        dosummary=dosummary,
        summary=summary,
        inboard=inboard,
        oarlength=oarlength,
        title=name,
        workoutsource=fileformat,
        notes=''
    )


    return id
