package org.springblade.common.auth.permission;

import org.springblade.common.cache.CachesService;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.support.JedisService;
import org.springblade.core.redis.cache.BladeRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.springblade.common.auth.permission.PermissionDefinition.CACHE_TYPE_URL_PERMISSION_CODE_MAPPING;

/**
 * 请求URL和权限点管理中心
 *
 * @author caiyihua
 */
@Component
@Slf4j
public class PermissionHandler {

//    @Autowired
    private CachesService cachesService = new CachesService();


    /**
     * 根据请求URL和请求方法类型获取权限编码
     *
     * @param requestUrl
     * @param requestMethod
     * @return
     */
    public String getPermissionCode(String requestUrl, String requestMethod) {
        Map<String, String> map =   cachesService.getFromCache(CACHE_TYPE_URL_PERMISSION_CODE_MAPPING, requestUrl);

        if (map != null && !map.isEmpty()) {
            String permissionCode = map.get(requestMethod);
            if (permissionCode == null) {
                permissionCode = map.get(RequestMethodTypeEnum.ALL.getText());
            }

            return permissionCode;
        }

        return null;
    }

    public String getPermissionCode(String requestUrl, String requestMethod, BladeRedis bladeRedis) {
        Map<String, String> map =  bladeRedis.get(CACHE_TYPE_URL_PERMISSION_CODE_MAPPING+":"+requestUrl);

        if (map != null && !map.isEmpty()) {
            String permissionCode = map.get(requestMethod);
            if (permissionCode == null) {
                permissionCode = map.get(RequestMethodTypeEnum.ALL.getText());
            }

            return permissionCode;
        }

        return null;
    }

}
