using System.Collections.Generic;
using Znyc.Cloudcar.Admin.Commons.Json;

namespace Znyc.Cloudcar.Admin.Commons.Tree
{
    public static class JsTree
    {
        public static List<JsTreeModel> JsTreeJson(this List<JsTreeModel> data)
        {
            return JsTreeJson(data, 0, "").ToList<JsTreeModel>();
        }

        private static string JsTreeJson(List<JsTreeModel> data, long ParentId, string blank)
        {
            List<JsTreeModel> list = new List<JsTreeModel>();
            JsTreeModel jsTreeModel = new JsTreeModel();
            List<JsTreeModel> ChildNodeList = data.FindAll(t => t.parent == ParentId);
            string tabline = "";
            if (!string.IsNullOrEmpty(ParentId.ToString()))
            {
                tabline = "";
            }

            if (ChildNodeList.Count > 0)
            {
                tabline = tabline + blank;
            }

            foreach (JsTreeModel entity in ChildNodeList)
            {
                jsTreeModel = entity;
                jsTreeModel.children = JsTreeJson(data, entity.id, tabline).ToList<JsTreeModel>();
                list.Add(jsTreeModel);
            }

            return list.ToJson();
        }
    }
}