package com.inspect.metadata.prodevmnt.util;

import com.inspect.metadata.prodevmnt.domain.vo.ProDeviceTreeSelectVO;
import com.inspect.base.core.utils.StringUtils;

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

public class ProDeviceTreeSelectUtil {
    public static List<ProDeviceTreeSelectVO> buildDeviceTree(List<ProDeviceTreeSelectVO> areas) {
        List<ProDeviceTreeSelectVO> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        Iterator<ProDeviceTreeSelectVO> iterator = areas.iterator();

        ProDeviceTreeSelectVO area;
        while (iterator.hasNext()) {
            area = iterator.next();
            tempList.add(area.getDeviceId());
        }

        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<ProDeviceTreeSelectVO> list, ProDeviceTreeSelectVO t) {
        List<ProDeviceTreeSelectVO> childList = getChildList(list, t);
        t.setChildren(childList);

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

    }

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

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

        return tlist;
    }

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