package com.inspect.metadata.eqpbook.util;

import com.inspect.metadata.eqpbook.domain.vo.BasedataAreaEquTreeVo;
import com.inspect.base.core.utils.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class BasedataAreaEquTreeVoUtil {
    public static List buildAreaTree(List<BasedataAreaEquTreeVo> areas) {
        List<BasedataAreaEquTreeVo> returnList = new LinkedList<>();
        List<String> tempList = new ArrayList<>();
        Iterator<BasedataAreaEquTreeVo> iterator = areas.iterator();

        BasedataAreaEquTreeVo area;
        while (iterator.hasNext()) {
            area = iterator.next();
            tempList.add(area.getId());
        }

        iterator = areas.iterator();

        while (iterator.hasNext()) {
            area = iterator.next();
            if (!tempList.contains(area.getParentId())) {
                recursionFn(areas, area);
                returnList.add(area);
            }
        }

        if (returnList.isEmpty()) {
            returnList = areas;
        }

        return returnList;
    }

    private static void recursionFn(List<BasedataAreaEquTreeVo> list, BasedataAreaEquTreeVo t) {
        List<BasedataAreaEquTreeVo> childList = getChildList(list, t);
        t.setChildren(childList);

        for (BasedataAreaEquTreeVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }

    }

    private static List<BasedataAreaEquTreeVo> getChildList(List<BasedataAreaEquTreeVo> list, BasedataAreaEquTreeVo t) {
        List<BasedataAreaEquTreeVo> tlist = new ArrayList<>();

        for (BasedataAreaEquTreeVo n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }

        return tlist;
    }

    private static boolean hasChild(List<BasedataAreaEquTreeVo> list, BasedataAreaEquTreeVo t) {
        return !getChildList(list, t).isEmpty();
    }
}
