<?php

class Rbac_model extends Cf_Model
{

    const USER_PERMISSIONS_URL = '/rbac/user-permissions';
    const ROLE_PERMISSIONS_URL = '/role/%s/permissions';
    const PERMISSION_LIST_URL = '/rbac';

    private $permissions = false;

    public function __construct()
    {
        parent::__construct();
    }

    public function getUserPermissions()
    {
        try {
            if (!$this->permissions) {
                $permissions = $this->getRestClient()->get(self::USER_PERMISSIONS_URL);
                $this->permissions = json_decode($permissions, JSON_OBJECT_AS_ARRAY);;
            }
            return $this->permissions;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . " " . $e->getFile() . " line:" . $e->getLine());
            throw $e;
        }
    }

    public function getPermissionList()
    {
        try {
            $permissions = json_decode($this->getRestClient()->get(self::PERMISSION_LIST_URL), JSON_OBJECT_AS_ARRAY);
            $result = [];

            // group by application and group
            foreach ($permissions as $permission) {
                $result[$permission['application']][$permission['group']][] = $permission;
            }

            return $result;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . " " . $e->getFile() . " line:" . $e->getLine());
            throw $e;
        }
    }

    public function getRolePermissions($role)
    {
        try {
            $url = sprintf(self::ROLE_PERMISSIONS_URL, $role);
            $permissions = $this->getRestClient()->get($url);
            return json_decode($permissions, JSON_OBJECT_AS_ARRAY);
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . " " . $e->getFile() . " line:" . $e->getLine());
            throw $e;
        }
    }

    public function assignPermissions($role, array $permissions)
    {
        try {
            $url = sprintf(self::ROLE_PERMISSIONS_URL, $role);
            $this->getRestClient()->put($url, $permissions);
            return true;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . " " . $e->getFile() . " line:" . $e->getLine());
            throw $e;
        }
    }

    public function revokePermissions($role, array $permissions)
    {
        try {
            $url = sprintf(self::ROLE_PERMISSIONS_URL, $role);
            $this->getRestClient()->delete($url, $permissions);
            return true;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . " " . $e->getFile() . " line:" . $e->getLine());
            throw $e;
        }
    }


}
