#!/srv/venv/bin/python
import sys
import os
# If you find a solution that does not need the two paths, please comment!
sys.path.append('$path_to_root_of_project$')
sys.path.append('$path_to_root_of_project$/$project_name$')

os.environ['DJANGO_SETTINGS_MODULE'] = '$project_name$.settings'

import zipfile

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
#from rowers.mailprocessing import processattachments
import time
from django.conf import settings
from rowers.tasks import handle_sendemail_unrecognized
from django_mailbox.models import Mailbox,Message,MessageAttachment
from rowers.models import Workout, User, Rower, WorkoutForm,RowerForm,GraphImage,AdvancedWorkoutForm
from django.core.files.base import ContentFile

from rowsandall_app.settings import BASE_DIR

from rowingdata import rower as rrower
from rowingdata import main as rmain
from rowingdata import rowingdata as rrdata

from rowingdata import make_cumvalues
from rowingdata import summarydata,get_file_type

from scipy.signal import savgol_filter
from rowers.mailprocessing import make_new_workout_from_email,send_confirm

def rdata(file,rower=rrower()):
    try:
	res = rrdata(file,rower=rower)
    except IOError:
	res = 0

    return res



class Command(BaseCommand):
    def handle(self, *args, **options):
	res = []
	attachments = MessageAttachment.objects.all()
	cntr = 0
	for a in attachments:
            extension = a.document.name[-3:].lower()
	    donotdelete = 0
	    m = Message.objects.get(id=a.message_id)
	    from_address = m.from_address[0].lower()
	    name = m.subject
	    cntr += 1
	    # get a list of users
	    # theusers = User.objects.filter(email=from_address)
            ther = [
                r for r in Rower.objects.all() if r.user.email.lower() == from_address
            ]
	    for rr in ther:
                if extension == 'zip':
                    z = zipfile.ZipFile(a.document)
                    for f in z.namelist():
                        f2 = z.extract(f,path='media/')
                        title = os.path.basename(f2)
                        wid = [
                            make_new_workout_from_email(rr,f2[6:],title)
                        ]
                        res += wid
                        link = 'http://rowsandall.com/rowers/workout/'+str(wid[0])+'/edit'
                        try:
                            dd = send_confirm(rr.user,title,link)
                            time.sleep(10)
                        except:
                            try:
                                time.sleep(10)
                                dd = send_confirm(rr.user,title,link)
                            except:
                                pass

                else:
		# move attachment and make workout
		    try:
		        wid = [
                            make_new_workout_from_email(rr,
                                                        a.document,
                                                        name)
                        ]
                        res += wid
                        link = 'http://rowsandall.com/rowers/workout/'+str(wid[0])+'/edit'
                        
		    except:
			# replace with code to process error
			res += ['fail: '+name]
			donotdelete = 1
                    try:
                        dd = send_confirm(rr.user,name,link)
                        time.sleep(10)
                    except:
                        pass

	    # remove attachment
	    if donotdelete == 0:
		a.delete()

	    if m.attachments.exists()==False:
		# no attachments, so can be deleted
		m.delete()

	mm = Message.objects.all()
	for m in mm:
	    if m.attachments.exists()==False:
		m.delete()

	self.stdout.write(self.style.SUCCESS('Successfully processed email attachments'))
	

	
	
