using DevExpress.Web.Mvc;
using GreenTree.Nachtragsmanagement.Core.Domain.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GreenTree.Nachtragsmanagement.Web.Framework.Extension.DevExpress
{
    public static class TreeViewSettingsExtension
    {
        /// <summary>
        /// Extension method to build up a tree view of the available functions
        /// </summary>
        /// <param name="settings">The current TreeViewSettings.</param>
        /// <param name="functionList">Available functions.</param>
        public static void CreateGroupedFunctionList(this TreeViewSettings settings, IList<Function> functionList)
        {
            if (settings == null || functionList == null) return;

            var dynFunctions = functionList
                .Select(f => new
                {
                    Function = f,
                    SubFunctions = new List<dynamic>()
                })
                .ToList();

            var dictFunctions = dynFunctions.ToDictionary(g => g.Function.Name);
            foreach (var item in dynFunctions.Where(g => g.Function.GroupName != null))
            {
                dictFunctions[item.Function.GroupName].SubFunctions.Add(item);
            }
            var groupFunctions = dynFunctions.Where(g => g.Function.GroupName == null);

            foreach (var mainFunction in groupFunctions)
            {
                var node = settings.Nodes.Add(mainFunction.Function.Description, mainFunction.Function.Id.ToString());

                foreach (var subFunction in mainFunction.SubFunctions)
                    IterateGroupedFunction(node, subFunction);
            }
        }

        /// <summary>
        /// Recursive method to iterate each subFunction of a dynamic function tree and creates a corresponding node
        /// </summary>
        /// <param name="node">The current parent to be iterated.</param>
        /// <param name="functionContainer">The corresponding function tree.</param>
        private static void IterateGroupedFunction(MVCxTreeViewNode node, dynamic functionContainer)
        {
            var subNode = node.Nodes.Add(functionContainer.Function.Description, functionContainer.Function.Id.ToString());

            foreach (var subFunction in functionContainer.SubFunctions)
                IterateGroupedFunction(subNode, subFunction);
        }
    }
}
