package casbinauth

import (
	"git.rosy.net.cn/jx-callback/business/authz"
	"git.rosy.net.cn/jx-callback/business/authz/autils"
	"github.com/casbin/casbin"
	"github.com/casbin/casbin/errors"
)

type CasbinAuthz struct {
	enforcer *casbin.SyncedEnforcer
}

func New(modelFile string) (authObj authz.IAuthz, err error) {
	obj := &CasbinAuthz{}
	obj.enforcer, err = casbin.NewSyncedEnforcer(modelFile, NewAdapter())
	return obj, err
}

func (c *CasbinAuthz) AddRole4User(userID string, r *authz.RoleInfo) (err error) {
	_, err = c.enforcer.AddRoleForUser(userID, r.GetFullName())
	return err
}

func (c *CasbinAuthz) DeleteRole4User(userID string, r *authz.RoleInfo) (err error) {
	_, err = c.enforcer.DeleteRoleForUser(userID, r.GetFullName())
	return err
}

func (c *CasbinAuthz) GetUserRoleList(userID string) (roleList []*authz.RoleInfo, err error) {
	roleNameList, err := c.enforcer.GetRolesForUser(userID)
	if err == nil && len(roleNameList) > 0 {
		roleList = autils.FullRoleName2RoleList(roleNameList)
	}
	return roleList, err
}

func (c *CasbinAuthz) GetRoleUserList(r *authz.RoleInfo) (userIDList []string, err error) {
	// globals.SugarLogger.Debug(roleFullName)
	userIDList, err = c.enforcer.GetUsersForRole(r.GetFullName())
	if err == errors.ERR_NAME_NOT_FOUND {
		err = nil
	}
	return userIDList, err
}

// func (c *CasbinAuthz) GetAllRoleList() (roleList []*authz.RoleInfo) {
// 	return authz.FullRoleName2RoleList(c.enforcer.GetAllRoles())
// }
