package cn.ibizlab.codegen.model;

import net.ibizsys.model.dataentity.logic.*;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class LogicNodeModel extends BaseModel {

    private LogicModel logicModel;

    private List<String> ruleGlobalParams = new ArrayList<>();


    public LogicNodeModel(LogicModel logicModel, IPSDELogicNode iPSDELogicNode) {
        this.opt = iPSDELogicNode;
        this.logicModel = logicModel;
        this.setCodeName(iPSDELogicNode.getCodeName());
        this.setName(iPSDELogicNode.getName());
        this.setId(String.format("%1$s-%2$s", logicModel.getCodeName(), iPSDELogicNode.getCodeName()));

    }

    public String getLogicNodeType() {
        return this.getPSDELogicNode().getLogicNodeType();
    }

    public LogicModel getLogicModel() {
        return logicModel;
    }

    public IPSDELogicNode getPSDELogicNode() {
        return (IPSDELogicNode) opt;
    }


    public String getRawSql() {
        String strSql = null;
        if (this.getPSDELogicNode() instanceof IPSDERawSqlCallLogic) {
            IPSDERawSqlCallLogic iPSDERawSqlCallLogic = (IPSDERawSqlCallLogic) this.getPSDELogicNode();
            strSql = iPSDERawSqlCallLogic.getSql();
            if (!CollectionUtils.isEmpty(iPSDERawSqlCallLogic.getPSDELogicNodeParams())) {
                int i = 0;
                while (strSql.indexOf("?") > -1) {
                    strSql = strSql.replaceFirst("\\?", String.format("#{et.param%s}", String.valueOf(i)));
                    i++;
                }
            }
        }
        if (this.getPSDELogicNode() instanceof IPSDERawSqlAndLoopCallLogic) {
            IPSDERawSqlAndLoopCallLogic iPSDERawSqlAndLoopCallLogic = (IPSDERawSqlAndLoopCallLogic) this.getPSDELogicNode();
            strSql = iPSDERawSqlAndLoopCallLogic.getSql();
            if (!CollectionUtils.isEmpty(iPSDERawSqlAndLoopCallLogic.getPSDELogicNodeParams())) {
                int i = 0;
                while (strSql.indexOf("?") > -1) {
                    strSql = strSql.replaceFirst("\\?", String.format("#{et.param%s}", String.valueOf(i)));
                    i++;
                }
            }
        }
        return strSql;
    }

    public String getAppName(){
        String strAppName = "";
        if (this.getPSDELogicNode() instanceof IPSDEStartWFLogic) {
            IPSDEStartWFLogic iPSDEStartWFLogic = (IPSDEStartWFLogic)this.getPSDELogicNode();
        }
        return strAppName;
    }

}
