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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.seer.teach.common.data.permission.rule.DataPermissionRule;
import com.seer.teach.common.data.permission.rule.DataPermissionRuleFactory;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.schema.Table;

import java.util.List;


@RequiredArgsConstructor
public class DataPermissionRuleHandler implements MultiDataPermissionHandler {

    private final DataPermissionRuleFactory ruleFactory;
    private static final String MYSQL_ESCAPE_CHARACTER = "`";
    @Override
    public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
        List<DataPermissionRule> rules = ruleFactory.getDataPermissionRule(mappedStatementId);
        if (CollUtil.isEmpty(rules)) {
            return null;
        }
        Expression allExpression = null;
        for (DataPermissionRule rule : rules) {
            String tableName = getTableName(table);
            if (!rule.getTableNames().contains(tableName)) {
                continue;
            }
            Expression oneExpress = rule.getExpression(tableName, table.getAlias());
            if (oneExpress == null) {
                continue;
            }
            if(rule.getCondition().matches()){
                allExpression = allExpression == null ? oneExpress : new AndExpression(allExpression, oneExpress);
            }
        }
        return allExpression;
    }

    public String getTableName(Table table) {
        String tableName = table.getName();
        if (tableName.startsWith(MYSQL_ESCAPE_CHARACTER) && tableName.endsWith(MYSQL_ESCAPE_CHARACTER)) {
            tableName = tableName.substring(1, tableName.length() - 1);
        }
        return tableName;
    }
}