# passerelle - uniform access to multiple data sources 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/>.

from cmislib.exceptions import ObjectNotFoundException
from django.http import Http404
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView

from .models import CmisConnector


class CmisTypeView(TemplateView):
    model = CmisConnector
    template_name = 'cmis/cmis_type.html'

    def dispatch(self, request, *args, **kwargs):
        self.connector = CmisConnector.objects.get(slug=kwargs['connector_slug'])
        with self.connector.get_cmis_gateway() as cmis_gateway:
            self.cmis_gateway = cmis_gateway
            return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        type_id = request.GET.get('id')
        if type_id:
            try:
                self.current_type = self.cmis_gateway.repo.getTypeDefinition(type_id)
            except ObjectNotFoundException:
                raise Http404(_('Cmis type not found.'))
        else:
            self.current_type = None
        return super().get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['object'] = self.connector
        if self.current_type:
            ctx['current_type'] = self.current_type
            properties = self.current_type.properties.values()
            ctx['current_properties'] = sorted(properties, key=lambda x: x.id)
            ctx['children_types'] = self.cmis_gateway.repo.getTypeChildren(self.current_type.id)
        else:
            ctx['children_types'] = self.cmis_gateway.repo.getTypeDefinitions()
        return ctx
