# 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 django.core.exceptions import PermissionDenied
from django.http import Http404, JsonResponse
from django.views.generic import DetailView, View

from passerelle.base.models import Job
from passerelle.utils import is_authorized
from passerelle.views import get_all_apps


class JobDetailView(DetailView):
    model = Job

    def error(self, message):
        return JsonResponse({'err': 1, 'err_desc': message})

    def get(self, *args, **kwargs):
        try:
            job = self.get_object()
        except Http404 as exc:
            return self.error(str(exc))
        if not is_authorized(self.request, job.resource, 'can_access'):
            raise PermissionDenied
        data = {
            'id': job.id,
            'resource': job.resource.__class__.__name__,
            'parameters': job.parameters,
            'status': job.status,
            'status_details': job.status_details,
            'update_timestamp': job.update_timestamp,
            'done_timestamp': job.done_timestamp,
        }
        return JsonResponse({'err': 0, 'data': data})


class StatisticsListView(View):
    def get(self, request, *args, **kwargs):
        sources = []
        for app in get_all_apps():
            for connector in app.objects.all():
                if hasattr(connector, 'get_statistics_entries'):
                    sources.extend(connector.get_statistics_entries(request))
        return JsonResponse({'data': sources})
