import datetime, pytz


def dateIsoUTC(myDate):
    tz = pytz.timezone("Europe/Paris")
    tDate = tz.localize(datetime.datetime.strptime(myDate, '%Y-%m-%d %H:%M:%S'))
    return tDate.isoformat()


def get_partners_with_makeups_to_come(api):
    """Returns a dictionary with : keys = the partners ids having at least one makeup to come ; values = #makeups_to_come"""
    shift_data = get_scheduled_makeups(api)
    count_dic = {}
    for value in shift_data:
        if value['partner_id'][0] in count_dic:
            count_dic[value['partner_id'][0]] = count_dic[value['partner_id'][0]] + 1
        else:
            count_dic[value['partner_id'][0]] = 1
    return count_dic


def get_shift_partner(api, id, start_date=None, end_date=None):
    """Récupère les shift du membre"""
    shifts = []
    is_ftop = False
    not_before = datetime.datetime.now().isoformat()
    if start_date:
        not_before = start_date.isoformat()
    fields = ['date_begin', 'date_end',
              'shift_id', 'shift_type', 'partner_id', "id", "associate_registered", "is_makeup"]  # res.partner
    cond = [['partner_id.id', '=', id], ['state', '=', 'open'],
            ['date_begin', '>', not_before]]
    if end_date:
        cond.append(['date_begin', '<', end_date.isoformat()])
    shiftData = api.search_read('shift.registration', cond, fields, order="date_begin ASC")
    for s in shiftData:
        if not ('Equipe volante' in s['shift_id'][1]):
            shifts.append(s)
        else:
            is_ftop = True
    return [shifts, is_ftop]


def get_exempted_ids_from(api, partner_ids):
    cond = [['id', 'in', partner_ids],
            ['cooperative_state', 'in', ['exempted']]]
    fields = ['id']
    return api.search_read('res.partner', cond, fields)


def get_scheduled_makeups(api, partner_ids=None):
    c = [["is_makeup", "=", True], ["state", "=", "open"], ['date_begin', '>', datetime.datetime.now().isoformat()]]
    if partner_ids:
        c.append(["partner_id", "in", partner_ids])
    f = ['id', 'shift_id', 'partner_id']
    res_shift_ids = api.search_read("shift.registration", c, f)
    return res_shift_ids
