# 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/>.

from urllib.parse import urljoin

import zeep
from django.db import models
from django.utils.translation import gettext_lazy as _

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

from . import utils


class ESiriusSwi(BaseResource):
    base_url = models.URLField(_('Base API URL'), help_text=_('with trailing slash'))
    verify_cert = models.BooleanField(default=True, verbose_name=_('Check HTTPS Certificate validity'))

    category = _('Business Process Connectors')

    class Meta:
        verbose_name = 'eSirius sitewaitingindicator'

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

    def check_status(self):
        wsdl_url = urljoin(self.base_url, 'v1.0?wsdl')
        response = self.requests.get(wsdl_url)
        response.raise_for_status()

    def get_client(self):
        wsdl_url = urljoin(self.base_url, 'v1.0?wsdl')
        return self.soap_client(wsdl_url=wsdl_url, settings=zeep.Settings(strict=False))

    def call(self, service, **kwargs):
        client = self.get_client()
        method = getattr(client.service, service)
        try:
            return method(**kwargs)
        except Exception as e:
            raise APIError(e)

    @endpoint(
        description=_('Returns indicators for all the sites'),
        perm='can_access',
    )
    def get_all_indicators(self, request):
        response = self.call('getAllIndicators')
        data = []
        for item_src in response or []:
            item_dest = {}
            for key in [
                'cumulatedWaitingVisitorNumber',
                'estimatedAvgWaitingTime',
                'estimatedMaxWaitingTime',
                'estimatedWaitingTimeForNextTicket',
                'name',
                'realAvgWaitingTime',
                'realMaxWaitingTime',
                'resourceNumber',
                'serviceWaitingIndicatorWSList',
                'siteCode',
                'waitingVisitorNumber',
                'weekHoursWS',
            ]:
                item_dest[key] = item_src[key]
            utils.compute_status(item_dest)
            data.append(item_dest)
        return {'err': 0, 'data': data}
