package cn.ibizlab.codegen.model;


import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.app.view.IPSAppViewRef;
import net.ibizsys.model.control.IPSControl;
import net.ibizsys.model.control.IPSControlContainer;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

    public CtrlModel(AppModel appModel,IPSControl psControl)
    {
        this.opt=psControl;
        this.app=appModel;
        this.setCodeName(psControl.getCodeName());
        this.setName(psControl.getName());

        if(psControl.getPSAppDataEntity()!=null)
            folder=new LabelExt(psControl.getPSAppDataEntity().getCodeName());
        else
            folder=new LabelExt("app");

        this.setId(String.format("%1$s-%2$s-%3$s-%4$s",app.getCodeName(),folder,psControl.getName(),psControl.getCodeName()));

        if(psControl instanceof IPSControlContainer){
            List<IPSAppViewRef> IPSAppViewRefs = ((IPSControlContainer)psControl).getPSAppViewRefs();
            if(IPSAppViewRefs != null && IPSAppViewRefs.size() >0){
                IPSAppViewRefs.forEach(appViewRef ->{
                    if(viewRefMap.get(appViewRef.getRefPSAppView().getId()) == null){
                        viewRefMap.put(appViewRef.getRefPSAppView().getId(),appViewRef);
                    }
                });
            }
        }
    }

    public Map<String,CtrlModel> ctrlsMap = new LinkedHashMap();

    private AppModel app;

    private AppEntityModel appEntity;

    private LabelExt folder;

    private Map<String, IPSAppViewRef> viewRefMap = new LinkedHashMap();

    public CtrlModel addCtrl(String codeName,CtrlModel ctrlModel)
    {
        if(!ctrlsMap.containsKey(codeName))
            ctrlsMap.put(codeName,ctrlModel);
        return this;
    }

    public Collection<CtrlModel> getCtrls()
    {
        return ctrlsMap.values();
    }

    public IPSControl getControl()
    {
        return (IPSControl)opt;
    }

    public String getTempFilter() {
        String name = this.getControl().getName();
        if ("QUICKSEARCHFORM".equals(name.toUpperCase())) {
            return "QUICKSEARCHFORM";
        } else {
            return this.getControl().getControlType();
        }
    }

    public Collection<IPSAppViewRef> getAppViewRefs(){
        return this.viewRefMap.values();
    }

}
