from datetime import date, datetime
from decimal import Decimal

def normalize_invoice(invoice, family_id, historical=False):
    invoice_id = '%s-%s' % (family_id, invoice['NOFACTURE'])
    invoice['id'] = invoice_id
    invoice['total_amount'] = Decimal(invoice['FMONTANT'])
    invoice['amount'] = Decimal(invoice['RESTEAPAYER'])
    invoice['display_id'] = invoice['NOFACTURE']
    invoice['has_pdf'] = invoice['FPDF'] == 'O'
    invoice['created'] = datetime.strptime(invoice['FEMISSION'], '%d/%m/%Y')
    invoice['label'] = invoice['FLIBELLE']
    invoice['pay_limit_date'] = datetime.strptime(invoice['FECHEANCE'], '%d/%m/%Y').date()
    if historical:
        invoice['online_payment'] = False
        invoice['paid'] = True
    else:
        invoice['online_payment'] = invoice['amount'] > 0 and invoice['pay_limit_date'] >= date.today()
        invoice['paid'] = False
    return {invoice_id: invoice}

def normalize_person(person):
    person['first_name'] = person['prenom']
    person['last_name'] = person['nom']
    person['birthdate'] = person['naissance']
    person['sex'] = person['sexe']
    person['address'] = '%(norue)s, %(voie)s, %(codepostal)s %(ville)s' % person
    person['city'] = person['ville']
    person['post_code'] = person['codepostal']
    person['email'] = person['mail']
    person['phone'] = person['telfixe']
    person['cellphone'] = person['telportable']
    return person
