using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;

namespace Kairos.Ui.Data.Grid
{
    public static class ColumnHelpers
    {
        public static object ExtractValue(ExpandoObject root, string fullPath)
        {
            #region Parameters Checks

            // Check if parameters are NULL
            if (root == null || fullPath == null)
            {
                throw new ArgumentNullException();
            }

            // Check empty object
            var rootDictionary = (IDictionary<string, object>)root;

            if (rootDictionary.Count == 0)
            {
                throw new ArgumentException("Empty object", "root");
            }

            // Check empty path
            if (String.IsNullOrWhiteSpace(fullPath))
            {
                throw new ArgumentException("Empty path", "fullPath");
            }

            #endregion

            // Done
            return ExtractValue(root, fullPath.Split("."));
        }

        private static object ExtractValue(IDictionary<string, object> root, string[] pathParts)
        {
            #region Parameters Checks

            // Valid property name ?
            if (!root.ContainsKey(pathParts[0]))
            {
                throw new ArgumentException("Not exists", "root");
            }

            #endregion

            // Value
            var value = root[pathParts[0]];

            // Final Part ?
            if (pathParts.Length == 1)
            {
                return value;
            }
            else
            {
                // Iterate for next step
                if (value is ExpandoObject newRoot)
                {
                    return ExtractValue(newRoot, pathParts[1..]);
                }
                else
                {
                    throw new ArgumentException("Not a navigation path", "root");
                }
            }
        }
    }
}
