
package com.jeelowcode.framework.plus.build.build.ddl;

import com.jeelowcode.framework.plus.build.ISQLExpression;
import com.jeelowcode.framework.plus.build.buildmodel.SQLInterpretContext;
import com.jeelowcode.framework.plus.build.buildmodel.ddl.SqlInfoCreateIndexModel;
import com.jeelowcode.framework.plus.entity.DbColunmTypesEntity;
import com.jeelowcode.framework.plus.utils.PlusUtils;
import com.jeelowcode.framework.plus.core.model.SqlFormatModel;
import com.jeelowcode.framework.utils.utils.FuncBase;
import net.sf.jsqlparser.JSQLParserException;

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

/***
 * 索引相关
 */
public class BuildCreateIndex implements ISQLExpression<List<SqlFormatModel>> {



    @Override
    public List<SqlFormatModel> interpret(SQLInterpretContext context) throws JSQLParserException {
        SqlInfoCreateIndexModel model = context.getCreateIndexModel();
        DbColunmTypesEntity dbColunmTypes = context.getDbColunmTypes();
        if(FuncBase.isEmpty(model)){
            return null;
        }
        //存在自定义ddl
        List<String> executeDdlList = model.getExecuteDdlList();
        if(FuncBase.isNotEmpty(executeDdlList)){
            return PlusUtils.ddl2SqlFormatModel(executeDdlList);
        }

        String symbol = dbColunmTypes.getSymbol();
        Boolean upperFlag = dbColunmTypes.getUpperFlag();

        String tableName = FuncBase.concatSymbol(model.getTableName(),symbol,upperFlag);
        String indexName = FuncBase.concatSymbol(model.getIndexName(),symbol,upperFlag);
        String indexType = model.getIndexType();
        String schemaName = FuncBase.concatSymbol(context.getSchemaName(),symbol);


        List<String> indexFieldCodeList = model.getIndexFieldCodeList();

        List<String> list = indexFieldCodeList.stream()
                .map(key -> FuncBase.concatSymbol( key , symbol,upperFlag))
                .collect(Collectors.toList());

        String str = "CREATE INDEX %s ON %s.%s (%s)";
        if(FuncBase.isNotEmpty(indexType) && "UNIQUE".equals(indexType.toUpperCase())){//唯一
            str = "CREATE UNIQUE INDEX %s ON %s.%s (%s)";
        }

        String ddl = String.format(str, indexName, schemaName,tableName, String.join(",", list));

        return PlusUtils.ddl2SqlFormatModel(ddl);


    }

}
