package cn.skcks.matrix.v2.services.casbin;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@Data
public class Permission {

    @Getter
    @AllArgsConstructor
    public enum Identify {
        ROLE(CasbinService.ROLE, CasbinService.ROLE_PREFIX), USER(CasbinService.USER, CasbinService.USER_PREFIX);

        private final String identify;
        private final String prefix;

        public static String getRoleName(Identify identify, String name) {
            final String prefix = identify.getPrefix();
            return getRoleName(prefix, name);
        }

        public static String getRoleName(String prefix, String name) {
            return name.startsWith(prefix) ? name : prefix + name;
        }

        public static String getRawRoleName(String roleName) {
            for (Identify identify : Identify.values()) {
                if (roleName.startsWith(identify.getPrefix())) {
                    return StringUtils.removeStart(roleName, identify.getPrefix());
                }
            }

            return roleName;
        }

        @Override
        public String toString() {
            return identify;
        }
    }

    @JsonIgnore
    private Identify identify;

    @JsonIgnore
    private String name;
    private String system;
    private String url;
    private String method;

    @JsonIgnore
    public String[] getPolicyParam() {
        return new String[]{Identify.getRoleName(identify.getPrefix(), name), system, url, method};
    }

    @JsonIgnore
    public List<String> getPolicyParamList() {
        return new ArrayList<>() {{
            add(Identify.getRoleName(identify.getPrefix(), name));
            add(system);
            add(url);
            add(method);
        }};
    }
}
