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


def get_current_year():
    """ This function is intended to return the year of the next edition """
    return 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, type_date="arrival"):
        arrival, departure = False, False
        tab_result = list()
        if type_date == "arrival":
            # Let's say people should arrive until 2 day before
            arrival = True
            my_day_range = range(2, -1, -1)
        elif type_date == "departure":
            # Let's say people should go back home until 2 day after
            departure = True
            my_day_range = range(3)
        else:
            return tab_result

        if self.Sejour:
            arr_date = datetime.strftime(self.Sejour.arrival_time, "%d %B %Y")
            dep_date = datetime.strftime(self.Sejour.depart_time, "%d %B %Y")
        else:
            arr_date = datetime.strftime(self.CurrentEventYear.start_time, "%d %B %Y")
            dep_date = datetime.strftime(self.CurrentEventYear.end_time, "%d %B %Y")

        for one_day in my_day_range:
            if arrival:
                tmp_day = self.CurrentEventYear.end_time - timedelta(days=one_day)
            elif departure:
                tmp_day = self.CurrentEventYear.start_time + timedelta(days=one_day)
            day_name = datetime.strftime(tmp_day, "%A")
            day_num = datetime.strftime(tmp_day, "%d/%m/%y")
            day_string = datetime.strftime(tmp_day, "%d %B %Y")
            if arrival and arr_date == day_string:
                tab_result.append((day_num, day_name, 'selected="selected"'))
            elif departure and dep_date == day_string:
                tab_result.append((day_num, day_name, 'selected="selected"'))
            else:
                tab_result.append((day_num, day_name, ""))
        return tab_result

    def PossibleTime(self, type_date="arrival"):
        arr_time, dep_time = "10:00", "19:00"
        tab_result = list()

        if self.Sejour:
            arr_time = datetime.strftime(self.Sejour.arrival_time, "%H:%M")
            dep_time = datetime.strftime(self.Sejour.depart_time, "%H:%M")

        for hour in range(24):
            for minutes in range(0, 60, 10):
                str_time = "%.2d:%.2d" % (hour, minutes)
                disp_time = "%dh%.2d" % (hour, minutes)
                if type_date == "arrival" and str_time == arr_time:
                    tab_result.append((str_time, disp_time, 'selected="selected"'))
                elif type_date == "departure" and str_time == dep_time:
                    tab_result.append((str_time, disp_time, 'selected="selected"'))
                else:
                    tab_result.append((str_time, disp_time, ""))
        return tab_result

    def IsCheck(self, InputControl):
        list_control_a = ['Arrival', 'Departure']
        list_control_b = ['PMR', 'Cov', 'Bras', 'Other']
        if InputControl not in map(':'.join, itertools.product(list_control_a, list_control_b)):
            return ""
        if self.Sejour:
            if InputControl.startswith('Arrival'):
                ctrl_val = 2 ** list_control_b.index(InputControl[8:])
                if self.Sejour.arrival_check & ctrl_val == ctrl_val:
                    return "checked=\"checked\""
                else:
                    return ""
            elif InputControl.startswith('Departure'):
                ctrl_val = 2 ** list_control_b.index(InputControl[10:])
                if self.Sejour.depart_check & ctrl_val == ctrl_val:
                    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 """
        list_orga = []
        for num in range(0, len(self.Orga_tasks)):
            curs = 2 ** num
            if self.Sejour.orga_part & curs == curs:
                list_orga.append(self.Orga_tasks[num])
        return list_orga
