# -*- coding: utf8 -*-
from .models import DBSession, JM2L_Year, Sejour
from datetime import timedelta, datetime
import itertools
from jm2l.const import CurrentYear

class DummySejour(object):
    
    def __init__(self, event):
        self.Me = event['request'].user
        self.CurrentEventYear = DBSession.query(JM2L_Year).filter(JM2L_Year.state=='Ongoing').first()
        self.Sejour = None
        if self.Me:
            self.Sejour = DBSession.query(Sejour)\
                .filter(Sejour.user_id==self.Me.uid)\
                .filter(Sejour.for_year==self.CurrentEventYear.year_uid)\
                .first()

class Sejour_helpers(DummySejour):

    def __init__(self, event):
        super(Sejour_helpers, self).__init__(event)
        if self.Sejour and self.Sejour.arrival_time is None:
            self.Sejour = None
        
    def StartEvent(self):
        # This function return the start of the event
        return self.CurrentYear
    
    def PossibleDate(self, typedate="arrival"):
        arrival, departure = False, False
        TabResult = list()
        if typedate == "arrival":
            # Let's say people should arrive until 2 day before
            arrival = True
            myDayRange = xrange(2,-1,-1)
        elif typedate == "departure":
            # Let's say people should go back home until 2 day after
            departure = True            
            myDayRange = xrange(3)
        else:
            return TabResult
        
        if self.Sejour:
            ArrDate = datetime.strftime(self.Sejour.arrival_time,"%d %B %Y")
            DepDate = datetime.strftime(self.Sejour.depart_time,"%d %B %Y")
        else:
            ArrDate = datetime.strftime( self.CurrentEventYear.start_time,"%d %B %Y" )
            DepDate = datetime.strftime( self.CurrentEventYear.end_time,"%d %B %Y" )
        
        for oneday in myDayRange:
            if arrival:
                TmpDay = self.CurrentEventYear.end_time - timedelta(days=oneday)
            elif departure:
                TmpDay = self.CurrentEventYear.start_time + timedelta(days=oneday)
            DayName = datetime.strftime(TmpDay,"%A")
            DayNum = datetime.strftime(TmpDay,"%d/%m/%y")
            DayString = datetime.strftime(TmpDay,"%d %B %Y")
            if arrival and ArrDate==DayString:
                TabResult.append((DayNum, DayName, 'selected="selected"'))
            elif departure and DepDate==DayString:
                TabResult.append((DayNum, DayName, 'selected="selected"'))
            else:
                TabResult.append((DayNum, DayName, ""))
        return TabResult

    def PossibleTime(self, typedate="arrival"):
        ArrTime, DepTime = "10:00", "19:00"
        TabResult = list()
        
        if self.Sejour:
            ArrTime = datetime.strftime(self.Sejour.arrival_time,"%H:%M")
            DepTime = datetime.strftime(self.Sejour.depart_time,"%H:%M")
        
        for hour in range(24):
            for minutes in range(0,60,10):
                StrTime = "%.2d:%.2d" % (hour, minutes)
                DispTime = "%dh%.2d" % (hour, minutes)
                if typedate == "arrival" and StrTime==ArrTime:
                    TabResult.append( (StrTime, DispTime, 'selected="selected"') )
                elif typedate == "departure" and StrTime==DepTime:
                    TabResult.append( (StrTime, DispTime, 'selected="selected"') )
                else:
                    TabResult.append( (StrTime, DispTime, "") )
        return TabResult

    def IsCheck(self, InputControl):
        ListControlA = ['Arrival', 'Departure']
        ListControlB = ['PMR', 'Cov', 'Bras', 'Other']
        if InputControl not in map(':'.join, itertools.product(ListControlA, ListControlB)):
            return ""
        if self.Sejour:
            if InputControl.startswith('Arrival'):
                CtrlVal = 2**ListControlB.index(InputControl[8:])
                if self.Sejour.arrival_check & CtrlVal == CtrlVal:
                    return "checked=\"checked\""
                else:
                    return ""
            elif InputControl.startswith('Departure'):
                CtrlVal = 2**ListControlB.index(InputControl[10:])
                if self.Sejour.depart_check & CtrlVal == CtrlVal:
                    return "checked=\"checked\""
                else:
                    return ""
            else:
                return ""
        else:
            return ""

class Orga_helpers(DummySejour):

    def __init__(self, event):
        super(Orga_helpers, self).__init__(event)
        self.Orga_tasks = [
            u"Participer au fléchage de l'événement.",
            u"Faire les courses.",
            u"Participer à l'accueil des visiteurs.",
            u"Accompagner, Guider les visiteurs.",
            u"Accompagner, Guider les intervenants.",
            u"Déplacer le matériel / le mobilier",
            u"Monter / Démonter les stands",
            u"Participer à la préparation / à vider les poubelles",
            u"Participer à la préparation / à vider les salles de conférence",
            u"Participer à la prise de son/vidéo des conférenciers.",
            u"Participer à poser, à repartir, à enlever les ralonges éléctriques.",
            u"Participer à poser, à repartir, à enlever les câbles réseau / le Wifi.",
            u"Remplir les frigos, s'assurer qu'ils soient toujours pleins. (Boissons)",
            u"Participer à la distribution des repas.",
            u"Faire du café et s'assurer de sa disponibilité.",
            u"Participer à la publication / au montage des vidéos des conférenciers.",
            u"Autres"
        ]        

    def IsChecked(self, nb):
        nb = 2**nb
        if self.Sejour and self.Sejour.orga_part:
            if self.Sejour.orga_part & nb == nb:
                return "checked=\"checked\""
            else:
                return ""
        else:
            return ""
        
    def ChoosedList(self):
        """ Return choice validated by user """
        ListOrga = []
        for num in range(0,len(self.Orga_tasks)):
            curs = 2**num
            if self.Sejour.orga_part & curs == curs:
                ListOrga.append(self.Orga_tasks[num])
        return ListOrga