
package com.lideeyunji.tool.framework.sql.build.build.ddl;

import com.lideeyunji.tool.framework.sql.build.ISQLExpression;
import com.lideeyunji.tool.framework.sql.build.buildmodel.SQLInterpretContext;
import com.lideeyunji.tool.framework.sql.build.buildmodel.ddl.SqlInfoPrimaryKeyModel;
import com.lideeyunji.tool.framework.sql.entity.DbColunmTypesEntity;
import com.lideeyunji.tool.framework.sql.utils.PlusUtils;
import com.lideeyunji.tool.framework.sql.core.model.SqlFormatModel;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import net.sf.jsqlparser.JSQLParserException;

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

/**
 * 主键相关
 */
public class BuildPrimaryKey implements ISQLExpression<List<SqlFormatModel>> {


    @Override
    public List<SqlFormatModel> interpret(SQLInterpretContext context) throws JSQLParserException {
        SqlInfoPrimaryKeyModel primaryKeyModel = context.getPrimaryKeyModel();

        if (FuncBase.isEmpty(primaryKeyModel)) {
            return null;
        }
        //存在自定义ddl
        List<String> executeDdlList = primaryKeyModel.getExecuteDdlList();
        if(FuncBase.isNotEmpty(executeDdlList)){
            return PlusUtils.ddl2SqlFormatModel(executeDdlList);
        }

        DbColunmTypesEntity dbColunmTypes = context.getDbColunmTypes();

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

        String tableName = FuncBase.concatSymbol(primaryKeyModel.getTableName(),symbol,upperFlag);
        String schemaName = FuncBase.concatSymbol(context.getSchemaName(),symbol);
        List<String> tmpkeyList = primaryKeyModel.getKeyList();
        if(FuncBase.isEmpty(tmpkeyList)){
            return null;
        }

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

        String str="ALTER TABLE %s.%s ADD PRIMARY KEY(%s)";
        String ddl = String.format(str,schemaName,tableName,String.join(",",keyList));
        return PlusUtils.ddl2SqlFormatModel(ddl);

    }
}
