package com.inspect.metadata.prodevmnt.util;

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

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

public class ProMainDevicePatrolEquTreeSelectUtil {
    public static List buildDeviceTree(List<ProMainDevicePatrolEquTreeSelect> treeS) {
        List<ProMainDevicePatrolEquTreeSelect> returnList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        Iterator<ProMainDevicePatrolEquTreeSelect> iterator = treeS.iterator();

        ProMainDevicePatrolEquTreeSelect area;
        while (iterator.hasNext()) {
            area = iterator.next();
            tempList.add(area.getDataId());
        }

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

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

        return returnList;
    }

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

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

    }

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

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

        return tlist;
    }

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