using System.Collections.Generic;

namespace Kit.Helpers.Extension.Entities
{
    public static class IdParentExtension
    {
        public static string BuildPath<TEntity>(this IIdParent<TEntity> item)
        {
            if (item != null)
            {
                return item.Parent.BuildPath().AddSufixIsNotEmpty(".") + item.Id.ToString("x9");
            }
            return string.Empty;
        }

        public static int BuildLevel<TEntity>(this IIdParent<TEntity> item)
        {
            if (item != null)
            {
                return item.Parent.BuildLevel() + 1;
            }
            return 0;
        }
    }

    public interface IIdParent<TEntity>
    {
        int Id { get; set; }
        IIdParent<TEntity> Parent { get; set; }
        int? ParentId { get; set; }
        int Level { get; }
        string Path { get; }
        IEnumerable<TEntity> Childs { get; set; }
    }

    public class IdParent<TEntity> : IIdParent<TEntity>
    {
        private string _path;
        private int _lvl;
        public int Id { get; set; }
        public IIdParent<TEntity> Parent { get; set; }
        public int? ParentId { get; set; }
        public int Level
        {
            get
            {
                if (_lvl == 0)
                {
                    _lvl = this.BuildLevel();
                }

                return _lvl;
            }
        }
        public IEnumerable<TEntity> Childs { get; set; }
        public string Path
        {
            get
            {
                if (_path.IsNullOrEmpty())
                {
                    _path = this.BuildPath();
                }

                return _path;
            }
        }
    }
}
