# passerelle.contrib.agoraplus
# -*- encoding: utf-8 -*-
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from datetime import datetime

def agoraize_date(date):
    try:
        return '%s' % datetime.strptime(date, '%Y-%m-%d').strftime('%d/%m/%Y')
    except ValueError:
        return ''

def dict_with_id_or_text(ref, textkey='nom'):
    if isinstance(ref, dict):
        if ref.get('id'):
            return {'id': ref.get('id')}
        return {'id': '', textkey: ref.get('text') or ''}
    return {'id': '', textkey: ''}

def agoraize_address(address):
    commune = dict_with_id_or_text(address.get('city'))
    commune['cp'] = address.get('post_code') or ''
    address_id = address.get('id') or ''
    if address_id.startswith('sas_'):
        address_id = ''
    return {
        'id': address_id,
        'numVoie': address.get('number') or '',
        'btq': dict_with_id_or_text(address.get('btq'), 'libelle'),
        'typeVoie': dict_with_id_or_text(address.get('type_of_street')),
        'voie': dict_with_id_or_text(address.get('street')),
        'complementAdresse': address.get('complements') or '',
        'commune': commune,
    }

def agoraize_adult(adult):
    adult_id = adult.get('id') or ''
    if adult_id.startswith('sas_'):
        adult_id = ''
    return {
        'id': adult_id,
        'email': adult.get('email') or '',
        'position': '%s' % adult.get('index') or '',
        'civilite': dict_with_id_or_text(adult.get('title')),
        'nom': adult.get('last_name') or '',
        'prenom': adult.get('first_name') or '',
        'dateNaissance': agoraize_date(adult.get('birthdate') or ''),
        'villeNaissance': adult.get('birth_city') or '',
        'paysNaissance': adult.get('birth_country') or '',
        'mobilePerso': adult.get('cellphone') or '',
        'fixPerso': adult.get('phone') or '',
        'adresse':  agoraize_address(adult.get('address') or {}),
        'profession': adult.get('profession') or '',
        'pcs': dict_with_id_or_text(adult.get('pcs')),
        'mobilePro': adult.get('work_cellphone') or '',
        'fixPro': adult.get('work_phone') or '',
        'employeur': adult.get('employer') or '',
        'telEmployeur': adult.get('employer_phone') or '',
        'adresseEmployeur': agoraize_address(adult.get('employer_address') or {}),
        'secu': '', # mandatory
    }

def agoraize_family(family):
    family_id = family.get('id') or ''
    if family_id.startswith('sas_'):
        family_id = ''
    res = {
        'id': family_id,
        'Representants': [agoraize_adult(adult) for adult in family.get('adults') or []],
        'Enfants': [],
        'Contacts': [],
        'Documents': [],
    }
    informations = family.get('informations', {})
    res['Informations complementaires'] = {
        'situationFamiliale': {'id': informations.get('situation', {}).get('id') or ''},
        'nbEnfants': informations.get('number_of_children') or '',
        'regime': {'id': ''},
        'numAlloc': '',
        'A.E.E.H': '0',
        'communicationAdresse': '0',
        'allocataire': '',
    }
    return res

def agoraize_child(child, representant_ids={}):
    child_id = child.get('id') or ''
    if child_id.startswith('sas_'):
        child_id = ''
    agora_child = {
        'id': child_id,
        'position': '%s' % child.get('index') or '',
        'nom': child.get('last_name') or '',
        'prenom': child.get('first_name') or '',
        'dateNaissance': agoraize_date(child.get('birthdate') or ''),
        'villeNaissance': child.get('birth_city') or '',
        'paysNaissance': child.get('birth_country') or '',
        'mobile': child.get('cellphone') or '',
        'contacts': [],
        'etablissementScolaire': {'id': '', 'designation': ''},
        'niveauInscription': {'id': '', 'designation': ''},
        'autoriteParentale': [],
    }
    for pid in child['parental_autorithy']:
        representant_id = representant_ids.get(pid['id']) or pid['id']
        agora_child['autoriteParentale'].append({'id': representant_id,
                                                 'type': 'representant'})
    if child.get('sex') == 'M':
        agora_child['sexe'] = u'Masculin'
    else:
        agora_child['sexe'] = u'Féminin'
    return agora_child

def agoraize_contact(contact, child_id_map={}):
    contact_id = contact.get('id') or ''
    if contact_id.startswith('sas_'):
        contact_id = ''
    agora_contact = {
        'id': contact_id,
        'email': contact.get('email', ''),
        'position': '%s' % (contact.get('index') or ''),
        'civilite': dict_with_id_or_text(contact.get('title')),
        'nom': contact.get('last_name') or '',
        'prenom': contact.get('first_name') or '',
        'adresse':  agoraize_address(contact.get('address') or {}),
        'mobilePerso': contact.get('cellphone') or '',
        'fixPerso': contact.get('phone') or '',
        'enfants': []
    }
    for child in contact.get('children', []):
        agora_contact['enfants'].append({
            'rang': '1', # XXX does it matter ?
            'id': child_id_map.get(child['id']) or child['id'],
            'lien': {'id': child['link']['id'], 'nom': ''},
            'interdiction': child.get('banned') and '1' or '0',
            'autoriteParentale': child.get('parental_authority') and '1' or '0',
        })
    return agora_contact
