
package com.jeelowcode.core.framework.config.validate;

import com.jeelowcode.core.framework.params.DbFormAddOrUpdateParam;
import com.jeelowcode.core.framework.service.IFrameService;
import com.jeelowcode.core.framework.utils.Func;
import com.jeelowcode.core.framework.utils.FuncWeb;
import com.jeelowcode.framework.exception.JeeLowCodeException;
import com.jeelowcode.framework.utils.adapter.IJeelowCodeValidate;
import com.jeelowcode.framework.utils.utils.FuncBase;
import com.jeelowcode.framework.utils.component.properties.JeeLowCodeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;

/**
 * 校验表名是否合法
 */
@Component
public class TableNameValidate implements IJeelowCodeValidate {

    @Autowired
    private IFrameService frameService;

    @Override
    public void validate(HttpServletRequest req) throws JeeLowCodeException {
        DbFormAddOrUpdateParam param = FuncWeb.getParameterBodyObj(req, DbFormAddOrUpdateParam.class);
        String tableName = param.getDbForm().getTableName().trim();
        if (FuncBase.isEmpty(tableName)) {
            throw new JeeLowCodeException("表名不允许为空");
        }

        if (!Func.checkTableName(tableName)) {
            StringJoiner joiner = new StringJoiner(",");
            JeeLowCodeProperties.getExcludeTableNames().forEach(joiner::add);
            String errorMsg = joiner.toString();
            throw new JeeLowCodeException(String.format("表名称不允许以【%s】开头", errorMsg));
        }
        //校验表名是否重复
        if (frameService.checkTable(tableName)) {
            String errorStr = String.format("数据库表【%s】已存在", tableName);
            throw new JeeLowCodeException(errorStr);
        }

    }
}
