package com.inspect.metadata.prodevmnt.util;

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

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

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

        ProDeviceTypeTreeSelectVO area;
        while (iterator.hasNext()) {
            area = iterator.next();
            tempList.add(area.getDeviceTypeId());
        }

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

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

    }

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

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

        return tlist;
    }

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