# passerelle.contrib.agoraplus
# 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

from .keywordize import keywordize_family

def finalize_address(address):
    address['text'] = u'{number}{btq[text]} {type_of_street[text]} {street[text]}'.format(**address).strip()
    address['full'] = address['text']
    end = u'{post_code} {city[text]}'.format(**address).strip()
    if end:
        address['full'] += u', ' + end
    return address

def finalize_person(person):
    person['text'] = u'%(first_name)s %(last_name)s' % person
    birthdate = person.get('birthdate')
    if birthdate:
        born = datetime.strptime(birthdate, '%Y-%m-%d')
        today = datetime.today()
        person['age_in_days'] = (today - born).days
        person['age'] = today.year - born.year - \
                int((today.month, today.day) < (born.month, born.day))
    if person.get('address'):
        person['address'] = finalize_address(person['address'])
    if person.get('employer_address'):
        person['employer_address'] = finalize_address(person['employer_address'])
    return person

def finalize_family(family):
    family['adults'] = [finalize_person(p) for p in family.get('adults') or []]
    family['children'] = [finalize_person(p) for p in family.get('children') or []]
    family['contacts'] = [finalize_person(p) for p in family.get('contacts') or []]
    if not family.get('address') and len(family['adults']) > 0:
        family['address'] = family['adults'][0]['address']
    keywordize_family(family)
    return family
