package cn.ibizlab.codegen.model;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.dataentity.IPSDataEntity;
import net.ibizsys.model.dataentity.service.IPSDEMethodDTO;
import net.ibizsys.model.dataentity.service.IPSDEMethodDTOField;
import net.ibizsys.model.dataentity.service.IPSDEServiceAPI;

import java.util.*;
import java.util.stream.Collectors;

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

    private ApiModel api;

    private ApiEntityModel apiEntity;

    String type = "";

    public ApiDtoModel(ApiEntityModel apiEntityModel, IPSDEMethodDTO iPSDEMethodDTO) {
        this.opt = iPSDEMethodDTO;
        this.type = iPSDEMethodDTO.getType();
        this.apiEntity = apiEntityModel;
        this.api = apiEntityModel.getApi();
        this.setCodeName(iPSDEMethodDTO.getName());
        this.setName(iPSDEMethodDTO.getName());
    }

    public String getLogicName() {
        return ((IPSDEServiceAPI) apiEntity.getOpt()).getLogicName();
    }

    public ApiEntityModel getApiEntity() {
        return apiEntity;
    }

    public IPSDataEntity getPSDataEntity() {
        return ((IPSDEMethodDTO) opt).getParentPSModelObject(IPSDataEntity.class);
    }

    public EntityModel getEntity() {
        return api.getSystem().getEntity(getPSDataEntity().getCodeName());
    }

    private List<ApiDtoFieldModel> ApiDtoFields;

    public List<ApiDtoFieldModel> getApiDtoFields() {
        if (ApiDtoFields == null) {
            ApiDtoFields = new ArrayList<>();
            if (((IPSDEMethodDTO) opt).getPSDEMethodDTOFields() != null) {
                for (IPSDEMethodDTOField iPSDEMethodDTOField : ((IPSDEMethodDTO) opt).getPSDEMethodDTOFields()) {
                    ApiDtoFieldModel apiDtoFieldModel = new ApiDtoFieldModel(this, iPSDEMethodDTOField);
                    ApiDtoFields.add(apiDtoFieldModel);
                }
            }
        }
        return ApiDtoFields;
    }
}
