package com.handong.smartservice.component;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class RcTree {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    
    protected abstract Map<String, Object> makeNewNode(Map<String, Object> item);


    public Map<String, Object> searchTreeNode(List<Map<String, Object>> listRcTree, String key) {
        Map<String, Object> node = null;
        
        for(int i = 0; i < listRcTree.size(); i++) {
            node = listRcTree.get(i);
            if (key.compareTo((String)node.get("key")) == 0) {
                return node;
            }

            Object children = node.get("children");
            if (children != null) {
                Map<String, Object> parentNode = searchTreeNode((List<Map<String, Object>>)children, key);
                if (parentNode != null)
                    return parentNode;
            }
        }
        
        return null;
    }
    
    public List<Map<String, Object>> convert(List<Map<String, Object>> listTreeDb) {
        List<Map<String, Object>> listRcTree = new ArrayList<Map<String, Object>>();
        listTreeDb.forEach(item -> {
            Map<String, Object> newNode = makeNewNode(item);
            
            if (item.get("pid") == null || listRcTree.size() == 0) {
                listRcTree.add(newNode);
            }
            else {
                // search parent node
                final String pid = item.get("pid") != null ? item.get("pid").toString() : "";
                logger.debug("pid = " + pid);

                Map<String, Object> parentNode = searchTreeNode(listRcTree, pid);
                logger.debug("convert, parentNode = " + parentNode);

                if (parentNode != null) {
                    List<Map<String, Object>> children = null;
                    Object childrenNode = parentNode.get("children");
                    if (childrenNode == null) {
                        children = new ArrayList<Map<String, Object>>();
                    }
                    else {
                        children = (List<Map<String, Object>>)childrenNode;
                    }
                    children.add(newNode);
                    parentNode.put("children", children);
                }
            }
        });
        
        return listRcTree;
    }
}
