package casbin_service

import (
	"bwallet/models"
)

type CasbinRole struct {
	Id    int
	Ptype string
	V0    string
	V1    string
	V2    string
	V3    string
	V4    string
	V5    string
}

type AllowPermission struct {
	Path   string `json:"path"`
	Method string `json:"method"`
}

type SetPermission struct {
	Value            string            `json:"value"`
	AllowPermissions []AllowPermission `json:"allow_permissions"`
}

type PermissionsResp struct {
	Path   string `json:"path"`
	Method string `json:"method"`
}

func (r *CasbinRole) GetAllRolesRelation() ([]*models.Role, error) {
	roles, err := models.GetRoles(r.getMaps())
	if err != nil {
		return nil, err
	}

	return roles, nil
}

func (r *SetPermission) AddPolicy() error {
	rules := [][]string{}
	for _, v := range r.AllowPermissions {
		rules = append(rules, []string{r.Value, v.Path, v.Method})
	}
	models.RemovePolicy("p", 0, r.Value)
	models.AddPolicy(rules)
	return nil
}

func (r *CasbinRole) AddGroupingPolicy() error {
	models.RemoveGroupingPolicy("g", 0, r.V0)

	role := map[string]interface{}{
		"v0": r.V0,
		"v1": r.V1,
	}
	if err := models.AddGroupingPolicy(role); err != nil {
		return err
	}

	return nil
}

func (r *SetPermission) GetPermissions() []*PermissionsResp {
	tmp_permissions := models.GetPolicies("p", 0, r.Value)

	var permissions = []*PermissionsResp{}
	for _, v := range tmp_permissions {
		permission := &PermissionsResp{}
		permission.Method = v[2]
		permission.Path = v[1]

		permissions = append(permissions, permission)
	}
	return permissions
}

func (r *CasbinRole) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if r.Id != 0 {
		maps["id"] = r.Id
	}

	if r.Ptype != "" {
		maps["ptype"] = r.Ptype
	}

	if r.V0 != "" {
		maps["v0"] = r.V0
	}

	return maps
}
