# Passerelle - uniform access to data and services
# Copyright (C) 2020  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 xml.etree import ElementTree as ET

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

from ..models import Invoice


class Loader:
    def __init__(self, connector):
        self.connector = connector

    def clean(self, archive):
        if 'factures.xml' not in archive.namelist():
            raise ValidationError(_('Missing factures.xml file in zip.'))

    def load(self, archive):
        with archive.open('factures.xml') as fdxml:
            factures = ET.fromstring(fdxml.read())
        external_ids = []
        for facture in factures:
            external_id = facture.attrib['Reference']
            amount = facture.attrib['Montant'].replace(',', '.')
            date = datetime.datetime.strptime(facture.attrib['Date'], '%d/%m/%Y')
            limit_date = date + datetime.timedelta(days=62)
            invoice = {
                'total_amount': amount,
                'amount': amount,
                'issue_date': date,
                'pay_limit_date': limit_date,
                'online_payment': True,
                'no_online_payment_reason': None,
                'label': external_id,
            }
            Invoice.objects.update_or_create(
                resource=self.connector, external_id=external_id, defaults=invoice
            )
            external_ids.append(external_id)
        Invoice.objects.filter(resource=self.connector).exclude(external_id__in=external_ids).delete()
