# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2015  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.views.generic import DetailView as GenericDetailView

from passerelle import utils

from .models import FakeFamily


class PermissionDenied(Exception):
    err_code = 100
    http_status = 403


class FakeFamilyDetailView(GenericDetailView):
    model = FakeFamily
    template_name = 'passerelle/contrib/fake_family/detail.html'


class DumpView(GenericDetailView):
    model = FakeFamily

    def get(self, request, *args, **kwargs):
        data = self.get_object().jsondatabase
        return utils.response_for_json(request, data)


class DetailView(GenericDetailView):
    model = FakeFamily
    resource = None

    def get_data(self, request, *args, **kwargs):
        raise NotImplementedError

    @utils.to_json()
    def get(self, request, *args, **kwargs):
        self.resource = self.get_object()
        return {'data': self.get_data(request, *args, **kwargs)}


class LinkView(DetailView):
    def get_data(self, request, *args, **kwargs):
        nameid = request.GET.get('NameID')
        login = request.GET.get('login')
        password = request.GET.get('password')
        assert nameid is not None, 'missing NameID in query string'
        assert login is not None, 'missing login in query string'
        assert password is not None, 'missing password in query string'
        for adult_id, adult in self.resource.jsondatabase['adults'].items():
            if adult['login'] == login:
                if adult['password'] == password:
                    break
                raise PermissionDenied('bad password')
        else:
            raise PermissionDenied('unknown login')
        self.resource.jsondatabase['links'][nameid] = adult_id
        self.resource.save()
        return adult


class UnlinkView(DetailView):
    def get_data(self, request, *args, **kwargs):
        nameid = request.GET.get('NameID')
        assert nameid is not None, 'missing NameID in query string'
        if nameid not in self.resource.jsondatabase['links']:
            return 'ok (but there was no links)'
        del self.resource.jsondatabase['links'][nameid]
        self.resource.save()
        return 'ok'


class FamilyDetailView(DetailView):
    family_id = None

    def get_details(self, *args, **kwargs):
        raise NotImplementedError

    def get_data(self, request, *args, **kwargs):
        nameid = request.GET.get('NameID')
        assert nameid is not None, 'missing NameID in query string'
        family_id = self.resource.get_familyid_by_nameid(nameid)
        if family_id is None:
            return None  # nameid not linked to a family
        self.family_id = family_id
        return self.get_details(*args, **kwargs)


class FamilyView(FamilyDetailView):
    def get_details(self, *args, **kwargs):
        family = self.resource.jsondatabase['families'][self.family_id]
        adults = self.resource.get_list_of('adults', self.family_id)
        children = self.resource.get_list_of('children', self.family_id)
        return {
            'id': self.family_id,
            'keywords': family.get('keywords', []),
            'adults': adults,
            'children': children,
        }


class FamilyKeyView(FamilyDetailView):
    def get_details(self, key, *args, **kwargs):
        items = self.resource.get_list_of(key, self.family_id)
        return items
