# -*- coding: utf-8 -*-
#
# defivelo-intranet -- Outil métier pour la gestion du Défi Vélo
# Copyright (C) 2016 Didier Raboud <me+defivelo@odyx.org>
#
# 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 __future__ import unicode_literals

from django.core.exceptions import PermissionDenied
from rolepermissions.roles import AbstractUserRole
from rolepermissions.verifications import has_permission


def user_cantons(user):
    if has_permission(user, 'cantons_all'):
        return
    if has_permission(user, 'cantons_mine'):
        return [
            m.canton for m in user.managedstates.all()
        ]
    raise PermissionDenied


class StateManager(AbstractUserRole):
    available_permissions = {
        'cantons_all': False,
        'cantons_mine': True,

        'user_view_list': True,

        'orga_crud': True,
    }


class PowerUser(AbstractUserRole):
    available_permissions = {
        'cantons_all': True,
        'cantons_mine': True,

        'user_view_list': True,
        'user_detail_other': True,
        'user_edit_other': True,
        'user_create': True,
        'user_crud_dv_public_fields': True,
        'user_crud_dv_private_fields': True,
        'user_can_send_credentials': True,
        'user_can_resend_credentials': False,

        'home_article_crud': True,

        'orga_crud': True,

        'challenge_season_crud': True,
        'challenge_session_crud': True,
    }

@@ -1037,44 +1037,169 @@
  if 
-has_permission(user, 'cantons_all'):
+user.pk in user_cantons.cache:%0A        return user_cantons.cache%5Buser.pk%5D%0A%0A    if has_permission(user, 'cantons_all'):%0A        user_cantons.cache%5Buser.pk%5D = None
 %0A   
@@ -1263,22 +1263,45 @@
         
-return
+user_cantons.cache%5Buser.pk%5D =
  %5B%0A     
@@ -1360,16 +1360,59 @@
       %5D%0A
+        return user_cantons.cache%5Buser.pk%5D%0A
     rais
@@ -1431,16 +1431,41 @@
 Denied%0A%0A
+user_cantons.cache = %7B%7D%0A%0A
 %0Aclass S

Optimize the user_cantons function through a local cache