# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2019 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 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').date()
    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
