package com.seer.teach.common.data.permission.rule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.seer.teach.common.data.permission.annotation.DataPermission;
import com.seer.teach.common.data.permission.aop.DataPermissionContextHolder;
import lombok.RequiredArgsConstructor;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@RequiredArgsConstructor
public class DataPermissionRuleFactoryImpl implements DataPermissionRuleFactory {

    /**
     * 数据权限规则数组
     */
    private final List<DataPermissionRule> rules;

    /**
     * 数据权限条件判断器列表
     */
    private final List<DataPermissionCondition> conditions;

    @Override
    public List<DataPermissionRule> getDataPermissionRules() {
        return rules;
    }

    @Override
    public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) {
        if (CollUtil.isEmpty(rules)) {
            return Collections.emptyList();
        }
        DataPermission dataPermission = DataPermissionContextHolder.get();
        if (dataPermission == null) {
            return rules;

        }
        if (!dataPermission.enable()) {
            return Collections.emptyList();
        }

        if (ArrayUtil.isNotEmpty(dataPermission.includeRules())) {
            return rules.stream().filter(rule -> ArrayUtil.contains(dataPermission.includeRules(), rule.getClass()))
                    .collect(Collectors.toList());
        }
        if (ArrayUtil.isNotEmpty(dataPermission.excludeRules())) {
            return rules.stream().filter(rule -> !ArrayUtil.contains(dataPermission.excludeRules(), rule.getClass()))
                    .collect(Collectors.toList());
        }
        return rules;
    }

    @Override
    public List<DataPermissionCondition> getConditions() {
        return conditions;
    }
}
