# Copyright (C) 2017  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 json
import os

from django.core.files.storage import default_storage
from django.utils.translation import gettext_lazy as _

from passerelle.base.models import BaseResource
from passerelle.utils import SFTPField
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError

from .cityweb import (
    CERTIFICATE_TYPES,
    CONCERNED,
    DOCUMENT_TYPES,
    ORIGINS,
    SEXES,
    TITLES,
    CivilStatusApplication,
)


class CityWeb(BaseResource):
    category = _('Civil Status Connectors')
    remote_sftp = SFTPField(verbose_name=_('Remote SFTP directory for outgoing files'), blank=True)

    class Meta:
        verbose_name = "CityWeb - Demande d'acte d'état civil"

    @classmethod
    def get_verbose_name(cls):
        return cls._meta.verbose_name

    @endpoint(perm='can_access', methods=['post'], description=_('Create a demand'))
    def create(self, request, *args, **kwargs):
        payload = json.loads(request.body)
        # check mandatory keys
        for key in ('application_id', 'application_time', 'certificate_type'):
            if key not in payload:
                raise APIError('<%s> is required' % key)

        application = CivilStatusApplication(payload)
        filepath = application.save(self.basepath)
        if self.remote_sftp:
            with self.remote_sftp.client() as client:
                client.put(filepath, os.path.join(client.getcwd(), os.path.basename(filepath)))
        return {'data': {'demand_id': application.identifiant}}

    @property
    def basepath(self):
        return os.path.join(default_storage.path('cityweb'), self.slug)

    @endpoint(perm='can_access', description=_('Get title list'))
    def titles(self, request):
        return {'data': TITLES}

    @endpoint(perm='can_access', description=_('Get sex list'))
    def sexes(self, request):
        return {'data': SEXES}

    @endpoint(perm='can_access', description=_('Get concerned status list'))
    def concerned(self, request):
        return {'data': CONCERNED}

    @endpoint(perm='can_access', description=_('Get application origin list'))
    def origins(self, request):
        return {'data': ORIGINS}

    @endpoint(
        name='certificate-types',
        perm='can_access',
        description=_('Get certificate type list'),
        parameters={'exclude': {'example_value': 'REC'}},
    )
    def certificate_types(self, request, exclude=''):
        return {'data': [item for item in CERTIFICATE_TYPES if item.get('id') not in exclude.split(',')]}

    @endpoint(
        name='document-types',
        perm='can_access',
        description=_('Get document type list'),
        parameters={'exclude': {'example_value': 'EXTPL'}},
    )
    def document_types(self, request, exclude=''):
        return {'data': [item for item in DOCUMENT_TYPES if item.get('id') not in exclude.split(',')]}
