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

from django.utils.dateparse import parse_date as django_parse_date

from passerelle.utils.jsonresponse import APIError


def parse_date(date):
    try:
        parsed_date = django_parse_date(date)
    except ValueError as e:
        raise APIError('Invalid date: %r (%r)' % (date, e))
    if not parsed_date:
        raise APIError('date %r not iso-formated' % date)
    return parsed_date.isoformat()


class ElementFactory(etree.Element):
    def __init__(self, *args, **kwargs):
        text = kwargs.pop('text', None)
        namespace = kwargs.pop('namespace', None)
        if namespace:
            super().__init__(etree.QName(namespace, args[0]), **kwargs)
            self.namespace = namespace
        else:
            super().__init__(*args, **kwargs)
        if text:
            self.text = text

    def append(self, subelement, allow_new=True):

        if not allow_new:
            if isinstance(subelement.tag, etree.QName):
                found = self.find(subelement.tag.text)
            else:
                found = self.find(subelement.tag)

            if found is not None:
                return self

        super().append(subelement)
        return self

    def extend(self, elements):
        super().extend(elements)
        return self


def zipdir(path, input_files):
    """Zip directory"""
    basefiles = []
    for key in ('message', 'enveloppe', 'demande'):
        if key in input_files:
            basefiles.append(input_files[key])

    archname = path + '.zip'
    with zipfile.ZipFile(archname, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for file_ in basefiles:
            fpath = os.path.join(path, file_)
            if os.path.exists(fpath):
                zipf.write(fpath, file_)

        for file_ in os.listdir(path):
            if file_ not in basefiles:
                fpath = os.path.join(path, file_)
                zipf.write(fpath, os.path.basename(fpath))

    return archname


def get_file_content_from_zip(path, filename):
    """Rreturn file content"""
    with zipfile.ZipFile(path, 'r') as zipf:
        return zipf.read(filename)
