# -*- coding: utf-8 -*-
from flask_restful import abort
from base import GenericListResource, GenericDetailResource
from ..models import APIRole, APIUser


class RoleDetail(GenericDetailResource):
    """
    This resource represents the role details and update / delete operations
    """
    model = APIRole
    updatable_fields = ['is_active', 'valid_until', 'permissions']

    def delete_object(self, pk):
        if len(APIUser.manager.search(arguments={'roles': pk})) > 0:
            abort(409, message='Cannot delete role with key {}, it\'s assigned to one or more users'.format(pk))
        else:
            super(RoleDetail, self).delete_object(pk)


class RoleList(GenericListResource):
    """
    This resource represents the role list.
    POST requests to this resource will create a new role
    """
    model = APIRole
    enable_multipost = True


class APIUserDetail(GenericDetailResource):
    """
    This resource represents the apiuser details and update / delete operations
    """
    model = APIUser
    updatable_fields = ['is_active', 'is_superuser', 'roles']


class APIUserList(GenericListResource):
    """
    This resource represents the apiuser list.
    POST requests to this resource will create a new apiuser,
        if the key is not present, one is created.
    The key will be returned as clear text, but stored hashed.
    """
    model = APIUser
