package cn.ibizlab.core.lite.extensions.domain;

import cn.ibizlab.core.lite.extensions.model.DataModel;
import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class NestedArray extends ArrayList<ModelObj> {

    @JsonIgnore
    @JSONField(serialize = false)
    private DataModel dataModel;

    @JsonIgnore
    @JSONField(serialize = false)
    public DataModel getDataModel() {
        return dataModel;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    private ModelObj parent;

    @JsonIgnore
    @JSONField(serialize = false)
    public ModelObj getParent() {
        return parent;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public NestedArray setParent(ModelObj parent) {
        this.parent = parent;
        if(parent!=null&&this.getDataModel()==null)
            this.dataModel=(parent.getDataModel());
        return this;
    }

    public NestedArray getSubNested(String name)
    {
        NestedArray rt=new NestedArray();

        for(ModelObj modelObj:this)
        {
            NestedArray list=modelObj.getNested(name,false);
            if(list!=null)
                rt.addAll(list);
        }

        return rt;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public Timestamp getTimestamp()
    {
        Timestamp last = DataObject.getBeginDate();
        for(ModelObj sub:this)
            if(sub.getTimestamp().getTime()>last.getTime())
                last=sub.getTimestamp();
        return last;
    }

    public List<Object> get(String key)
    {
        List<Object> list=new ArrayList<>();
        if(key==null)
            return null;

        if(key.indexOf(".")>0)
        {
            String[] epair=key.toString().split("[.]");
            if(epair.length>=2)
            {
                String name=epair[0];
                String column=epair[1];
                this.forEach(modelObj -> {
                    Object obj=modelObj.getEntity(name).get(column);
                    list.add(obj);
                });
            }
        }
        return list;
    }


    public List<Object> get(String key,String cond)
    {
        List<Object> list=new ArrayList<>();
        if(key==null)
            return null;

        if(key.indexOf(".")>0)
        {
            String[] epair=key.toString().split("[.]");
            if(epair.length>=2)
            {
                String name=epair[0];
                String column=epair[1];
                this.forEach(modelObj -> {
                    if(modelObj.IF(cond))
                    {
                        Object obj=modelObj.getEntity(name).get(column);
                        list.add(obj);
                    }
                });
            }
        }
        return list;
    }

}
