package cn.ibizlab.codegen.model;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.dataentity.action.IPSDEAction;
import net.ibizsys.model.dataentity.action.IPSDELogicAction;
import net.ibizsys.model.dataentity.action.IPSDEScriptAction;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class ActionModel extends BaseModel{

    public ActionModel(EntityModel entityModel, IPSDEAction action)
    {
        this.opt=action;
        this.entity=entityModel;
        this.setCodeName(action.getCodeName());
        this.setName(action.getName());
        this.setId(String.format("%1$s-%2$s",entity.getCodeName(),action.getCodeName()));
    }

    public IPSDEAction getDEAction()
    {
        return (IPSDEAction)opt;
    }

    private EntityModel entity;

    public boolean isGetAction()
    {
        return codeName.toLowerCase().startsWith("get");
    }

    public Set<String> getLogics()
    {
        Set<String> validLogic=new HashSet<>();
        if(!ObjectUtils.isEmpty(getDEAction().getBeforePSDEActionLogics()))
        {
            getDEAction().getBeforePSDEActionLogics().forEach(logic->{
                if ((logic.isValid()  && logic.isInternalLogic() && logic.getPSDELogic().isEnableBackend()) ||
                (logic.getDstPSDE()!=null && logic.getDstPSDEAction()!=null && (!(logic.getDstPSDEAction() instanceof IPSDEScriptAction))))
                    validLogic.add((entity.codeName+this.codeName).toLowerCase()+"before.bpmn");
            });
        }
        if(!ObjectUtils.isEmpty(getDEAction().getAfterPSDEActionLogics()))
        {
            getDEAction().getAfterPSDEActionLogics().forEach(logic->{
                if ((logic.isValid()  && logic.isInternalLogic() && logic.getPSDELogic().isEnableBackend()) ||
                        (logic.getDstPSDE()!=null && logic.getDstPSDEAction()!=null && (!(logic.getDstPSDEAction() instanceof IPSDEScriptAction))))
                    validLogic.add((entity.codeName+this.codeName).toLowerCase()+"after.bpmn");
            });
        }
        if("DELOGIC".equalsIgnoreCase(getDEAction().getActionType())&&getDEAction() instanceof IPSDELogicAction)
        {
            validLogic.add((entity.codeName+this.codeName).toLowerCase()+"exec.bpmn");
        }
        return validLogic;
    }

}
