# coding=utf-8
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import PermissionDenied
from tEDataProj.inter import check_user_key_inter


class Auth_API_perms(BasePermission):
    """
    Allows access only users w full access.
    """

    def has_permission(self, request, view):

        if not request.user or request.user.is_anonymous or not request.user.is_active:
            return False

        # auth_data = request.query_params
        # if not check_user_key_inter(auth_data):
        #     raise PermissionDenied(code=403)

        user = request.user
        groups = user.groups.all()

        groups_name_list = groups.values_list('name', flat=True)

        if u'API 1С импорт' in groups_name_list:
            return False

        if view.basename == u'user':
            # if view.action in ('get_subordinate_staff',):
            #     return True

            if view.action in (
                    'get_sales_department_staff',) and u'Отдел продаж: Начальник отдела продаж' in groups_name_list:
                return True

            if view.action in ('create',):
                perm = user.has_perm('AuthApp.UI_managers_create')
                return perm

            if view.action in ('update', 'partial_update', 'add_communication_item'):
                perm = user.has_perm('AuthApp.UI_managers_modify')
                return perm

            if view.action in ('destroy',):
                perm = user.has_perm('AuthApp.UI_managers_delete')
                return perm

            if view.action in (
                    'retrieve', 'list', 'list_by_company_id', 'list_by_office_id', 'get_subordinate_staff',
                    'get_all_staff'):
                perm = user.has_perm('AuthApp.UI_managers_retrieve')
                return perm

            if view.action in ('get_sales_stat_by_productid', 'stat_list'):
                perm = user.has_perm('AuthApp.UI_managers_all_stat') or user.has_perm('AuthApp.UI_managers_self_stat')
                return perm

        # if view.basename == u'userprofile':
        #
        #     if view.action in ('create',):
        #         perm = user.has_perm('AuthApp.add_userprofile')
        #         return perm
        #
        #     if view.action in ('update', 'partial_update'):
        #         perm = user.has_perm('AuthApp.change_userprofile')
        #         return perm
        #
        #     if view.action in ('destroy',):
        #         perm = user.has_perm('AuthApp.delete_userprofile')
        #         return perm
        #
        #     if view.action in ('retrieve', 'list'):
        #         return True

        return False
