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

import datetime

from django.utils.timezone import localtime

from passerelle.contrib.utils import axel


def get_reference_year_from_date(booking_date):
    if booking_date.month <= 8:
        # between january and august, reference year is the year just before
        return booking_date.year - 1
    return booking_date.year


def normalize_invoice(invoice, family_id, historical=False, vendor_base=None):
    vendor = vendor_base or {}
    vendor.update(invoice)
    invoice_id = '%s-%s' % (family_id, invoice['IDFACTURE'])
    if historical:
        invoice_id = 'historical-%s' % invoice_id
    data = {
        'id': invoice_id,
        'display_id': str(invoice['IDFACTURE']),
        'label': invoice['FACTURATION'],
        'paid': False,
        'created': invoice['EMISSION'],
        'total_amount': invoice['MONTANT'],
        'has_pdf': invoice['EXISTEPDF'],
        'vendor': {'caluire-axel': vendor},
    }
    if historical:
        data.update(
            {
                'amount': 0,
                'pay_limit_date': '',
                'online_payment': False,
            }
        )
    else:
        date_now = localtime().date()
        online_payment = True
        if invoice['ECHEANCE']:
            date_pay_limit = datetime.datetime.strptime(invoice['ECHEANCE'], axel.json_date_format).date()
            if date_now > date_pay_limit:
                # date_pay_limit has been reached
                online_payment = False

        if invoice['ENCAISSE'] >= invoice['MONTANT']:
            # already paid
            online_payment = False

        data.update(
            {
                'amount': max(0, invoice['MONTANT'] - invoice['ENCAISSE']),
                'amount_paid': invoice['ENCAISSE'],
                'pay_limit_date': invoice['ECHEANCE'],
                'online_payment': online_payment,
            }
        )
    return data
