# Passerelle - uniform access to data 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/>.

import json

from django.views.generic import DetailView as GenericDetailView, View
from django.views.decorators.csrf import csrf_exempt

from passerelle import utils

from .models import MeyzieuNewsletters


class ManagementDetailView(GenericDetailView):
    model = MeyzieuNewsletters
    template_name = 'passerelle/contrib/meyzieu_newsletters/detail.html'


class DetailView(GenericDetailView):
    model = MeyzieuNewsletters

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

    @utils.protected_api('can_access')
    @utils.to_json('api')
    def get(self, request, *args, **kwargs):
        return self.get_data(request, *args, **kwargs)


class NewslettersTypesView(DetailView):

    def get_data(self, request, *args, **kwargs):
        return self.get_object().get_newsletters()


class NewslettersSubscriptionsView(DetailView):

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(NewslettersSubscriptionsView, self).dispatch(*args, **kwargs)

    @utils.protected_api('can_access')
    @utils.to_json('api')
    def delete(self, request, *args, **kwargs):
        email = request.GET.get('email')
        assert email, 'missing email parameter'
        obj = self.get_object()
        subscriptions = obj.get_subscriptions(email)
        for sub in subscriptions:
            sub['transports'] = []
        return obj.set_subscriptions(email, subscriptions)

    @utils.protected_api('can_access')
    @utils.to_json('api')
    def post(self, request, *args, **kwargs):
        email = request.GET.get('email')
        assert email, 'missing email parameter'
        data = json.loads(request.body)
        return self.get_object().set_subscriptions(email, data)

    def get_data(self, request, *args, **kwargs):
        return self.get_object().get_subscriptions(request.GET.get('email'))
