/*
 * *************************************************
 * Copyright (c) 2019 QMTH. All Rights Reserved.
 * Created by Deason on 2019-05-07 11:02:18.
 * *************************************************
 */

package cn.com.qmth.examcloud.core.questions.starter.config;

import cn.com.qmth.examcloud.api.commons.enums.DataRuleType;
import cn.com.qmth.examcloud.api.commons.security.bean.*;
import cn.com.qmth.examcloud.api.commons.security.enums.RoleMeta;
import cn.com.qmth.examcloud.commons.util.RegExpUtil;
import cn.com.qmth.examcloud.core.basic.api.UserDataRuleCloudService;
import cn.com.qmth.examcloud.core.basic.api.request.QueryUserDataRuleReq;
import cn.com.qmth.examcloud.core.basic.api.response.QueryUserDataRuleResp;
import cn.com.qmth.examcloud.support.CacheConstants;
import cn.com.qmth.examcloud.support.cache.CacheHelper;
import cn.com.qmth.examcloud.support.cache.bean.AppCacheBean;
import cn.com.qmth.examcloud.web.redis.RedisClient;
import cn.com.qmth.examcloud.web.security.ResourceManager;
import cn.com.qmth.examcloud.web.security.SecurityProperty;
import cn.com.qmth.examcloud.web.support.ApiInfo;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class ExamCloudResourceManager implements ResourceManager {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserDataRuleCloudService userDataRuleCloudService;

    static {
        SecurityProperty.loadProperties("security.properties");
    }

    @Override
    public AccessApp getAccessApp(Long appId) {
        AppCacheBean appCacheBean = CacheHelper.getApp(appId);
        AccessApp app = new AccessApp();
        app.setAppId(appCacheBean.getId());
        app.setAppCode(appCacheBean.getCode());
        app.setAppName(appCacheBean.getName());
        app.setSecretKey(appCacheBean.getSecretKey());
        app.setTimeRange(appCacheBean.getTimeRange());
        return app;
    }

    @Override
    public boolean isNaked(ApiInfo apiInfo, String mapping) {
        if (null == apiInfo) {
            return true;
        }

        if (mapping.matches(".*swagger.*")) {
            return true;
        }

        if (null != apiInfo) {
            if (apiInfo.isNaked()) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(User user, ApiInfo apiInfo, String mapping) {

        // 学生鉴权
        if (user.getUserType().equals(UserType.STUDENT)) {
            String key = "[s]" + mapping;
            return SecurityProperty.getBooleanProperty(key, false);
        }

        List<Role> roleList = user.getRoleList();

        if (CollectionUtils.isEmpty(roleList)) {
            return false;
        }

        for (Role role : roleList) {
            if (role.getRoleCode().equals(RoleMeta.SUPER_ADMIN.name())) {
                return true;
            }
        }

        // 权限组集合
        String privilegeGroups = SecurityProperty.getProperty(mapping);
        if (StringUtils.isEmpty(privilegeGroups)) {
            return true;
        }

        // 用户权限集合
        Set<String> rolePrivilegeList = Sets.newHashSet();
        Long rootOrgId = user.getRootOrgId();
        for (Role role : roleList) {
            String key = CacheConstants.CACHE_B_ROLE_PRIVILEGE + rootOrgId + "_" + role.getRoleId();
            String rolePrivileges = redisClient.get(key, String.class);

            List<String> rpList = RegExpUtil.findAll(rolePrivileges, "\\w+");
            rolePrivilegeList.addAll(rpList);
        }

        List<String> privilegeGroupList = RegExpUtil.findAll(privilegeGroups, "[^\\;]+");

        for (String pg : privilegeGroupList) {
            pg = pg.trim();
            if (StringUtils.isBlank(pg)) {
                continue;
            }

            List<String> pList = RegExpUtil.findAll(pg, "[^\\,]+");
            if (rolePrivilegeList.containsAll(pList)) {
                return true;
            } else {
                continue;
            }
        }

        return false;
    }

    @Override
    public UserDataRule loadUserDataRule(Long userId, DataRuleType dataRuleType) {
        QueryUserDataRuleReq req = new QueryUserDataRuleReq();
        req.setUserId(userId);
        req.setType(dataRuleType);
        QueryUserDataRuleResp resp = userDataRuleCloudService.queryUserDataRule(req);

        UserDataRule userDataRule = new UserDataRule();
        userDataRule.setGlobalStatus(resp.getGlobalStatus());
        userDataRule.setRefIds(resp.getRefIds());
        return userDataRule;
    }

}
