# authentic2 - versatile identity manager
# Copyright (C) 2010-2019 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.contrib import messages
from django.utils.translation import ugettext as _

from authentic2.models import Service

from . import forms, role_views, tables, views


class ServicesView(views.HideOUColumnMixin, views.BaseTableView):
    model = Service
    template_name = 'authentic2/manager/services.html'
    table_class = tables.ServiceTable
    search_form_class = forms.ServiceSearchForm
    permissions = ['authentic2.search_service']
    title = _('Services')

    def get_search_form_kwargs(self):
        kwargs = super().get_search_form_kwargs()
        kwargs['queryset'] = self.get_queryset()
        return kwargs


listing = ServicesView.as_view()


class ServiceView(
    views.SimpleSubTableView,
    role_views.RoleViewMixin,
    views.MediaMixin,
    views.FormNeedsRequest,
    views.FormView,
):
    search_form_class = forms.NameSearchForm
    model = Service
    pk_url_kwarg = 'service_pk'
    template_name = 'authentic2/manager/service.html'
    table_class = tables.ServiceRolesTable
    permissions = ['authentic2.view_service']
    form_class = forms.ChooseRoleForm
    success_url = '.'

    @property
    def title(self):
        return str(self.object)

    def get_table_queryset(self):
        return self.object.authorized_roles.all()

    def get(self, request, *args, **kwargs):
        result = super().get(request, *args, **kwargs)
        self.service = self.object
        return result

    def form_valid(self, form):
        role = form.cleaned_data['role']
        action = form.cleaned_data['action']
        if self.can_change:
            if action == 'add':
                if self.object.authorized_roles.filter(pk=role.pk).exists():
                    messages.warning(self.request, _('Role already authorized in this ' 'service.'))
                else:
                    self.object.add_authorized_role(role)
            elif action == 'remove':
                self.object.remove_authorized_role(role)
        else:
            messages.warning(self.request, _('You are not authorized'))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        kwargs['form'] = self.get_form()
        ctx = super().get_context_data(**kwargs)
        ctx['roles_table'] = tables.RoleTable(self.object.roles.all())
        return ctx


roles = ServiceView.as_view()


class ServiceEditView(views.BaseEditView):
    model = Service
    pk_url_kwarg = 'service_pk'
    template_name = 'authentic2/manager/form.html'
    title = _('Edit service')
    permissions = ['authentic2.change_service']
    fields = ['name', 'slug', 'ou', 'unauthorized_url']
    success_url = '..'


edit = ServiceEditView.as_view()
