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

namespace Wayne.Lib
{
    /// <summary>
    /// The IIdentifiableEntity represents an entity of some sort that has an integer ID and a possible parent.
    /// </summary>
    public interface IIdentifiableEntity
    {
        #region Properties

        /// <summary>
        /// The ID of the entity.
        /// </summary>
        int Id { get; }

        /// <summary>
        /// The main type of entity.
        /// </summary>
        string EntityType { get; }

        /// <summary>
        /// This is used by the logger and should never be set by implementing classes
        /// </summary>
        string FullEntityName { get; set; }

        /// <summary>
        /// A more refined type of the entity, e.g. a specific implementation or brand.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubType")]
        string EntitySubType { get; }

        /// <summary>
        /// Reference to a possible parent device.
        /// </summary>
        IIdentifiableEntity ParentEntity { get; }

        #endregion
    }

    /// <summary>
    /// A class implementing the IIdentifiableEntity interface.
    /// Also contains static properties and methods that handles IIdentifiableEntity.
    /// </summary>
    public class IdentifiableEntity : IIdentifiableEntity
    {
        #region Fields
        private readonly int id;
        private readonly string entityType;
        private readonly string entitySubType;
        private readonly IIdentifiableEntity parentEntity;
        #endregion

        #region Construction

        static IdentifiableEntity()
        {
            Empty = new IdentifiableEntity(NoId, string.Empty, string.Empty, null);
        }

        /// <summary>
        /// Construction
        /// </summary>
        /// <param name="id">The ID of the entity.</param>
        /// <param name="entityType">The main type of entity.</param>
        /// <param name="entitySubType">A more refined type of the entity, e.g. a specific implementation or brand.</param>
        /// <param name="parentEntity">Reference to a possible parent device.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubType")]
        public IdentifiableEntity(int id, string entityType, string entitySubType, IIdentifiableEntity parentEntity)
        {
            this.id = id;
            this.entityType = entityType;
            this.entitySubType = entitySubType;
            this.parentEntity = parentEntity;
        }

        #endregion

        #region IIdentifiableEntity Members

        /// <summary>
        /// The ID of the entity.
        /// </summary>
        public int Id
        {
            get { return id; }
        }

        /// <summary>
        /// The main type of entity.
        /// </summary>
        public string EntitySubType
        {
            get { return entitySubType; }
        }

        /// <summary>
        /// A more refined type of the entity, e.g. a specific implementation or brand.
        /// </summary>
        public string EntityType
        {
            get { return entityType; }
        }

        /// <summary>
        /// This is used by the logger and should never be set by inheriting classes
        /// </summary>
        public string FullEntityName { get; set; }

        /// <summary>
        /// Reference to a possible parent device.
        /// </summary>
        public IIdentifiableEntity ParentEntity
        {
            get { return parentEntity; }
        }

        #endregion

        #region Misc Static Members

        /// <summary>
        /// A value representing a non-Id.
        /// </summary>
        public const int NoId = int.MinValue;

        /// <summary>
        /// An empty IdentifiableEntity.
        /// </summary>
        public static IdentifiableEntity Empty { get; private set; }

        /// <summary>
        /// Gets an IIdentifiableEntity-array of the ancestors of the given entity.
        /// The first one in the list is the given entity itself, and the last one is the root-parent.
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static IIdentifiableEntity[] GetAncestorArray(IIdentifiableEntity entity)
        {
            List<IIdentifiableEntity> ancestors = new List<IIdentifiableEntity>();
            while (entity != null)
            {
                ancestors.Add(entity);
                entity = entity.ParentEntity;
            }
            return ancestors.ToArray();
        }

        /// <summary>
        /// Tests equality between two identifieable entities on the regards on the 
        /// Id, EntityType, EntitySubtype, and the parent ancestry.
        /// </summary>
        /// <param name="entity1"></param>
        /// <param name="entity2"></param>
        /// <returns></returns>
        public static bool Equals(IIdentifiableEntity entity1, IIdentifiableEntity entity2)
        {
            if (entity1 == null)
                throw new ArgumentNullException("entity1");
            if (entity2 == null)
                throw new ArgumentNullException("entity2");
            if (entity1 == entity2)
                return true;

            if (string.IsNullOrEmpty(entity1.FullEntityName))
            {
                entity1.FullEntityName = ToString(entity1, true);
            }
            if (string.IsNullOrEmpty(entity2.FullEntityName))
            {
                entity2.FullEntityName = ToString(entity2, true);
            }

            return entity1.FullEntityName == entity2.FullEntityName;
        }

        #endregion

        #region ToString

        /// <summary>
        /// Composes a string from this IIdentifiableEntity.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (string.IsNullOrEmpty(FullEntityName))
            {
                FullEntityName = ToString(this, true);
        }
            return FullEntityName;
        }

        /// <summary>
        /// Composes a string from an IIdentifiableEntity.
        /// </summary>
        /// <param name="entity">The entity to convert to a string.</param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
        public static string ToString(IIdentifiableEntity entity)
        {
            return ToString(entity, false);
        }

        /// <summary>
        /// Composes a string from an IIdentifiableEntity, possibly with the ancestors included.
        /// </summary>
        /// <param name="entity">The entity to convert to a string.</param>
        /// <param name="ancestors">Should the ancestors be included?</param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
        public static string ToString(IIdentifiableEntity entity, bool ancestors)
        {
            if ((entity == null) || (entity == Empty))
                return string.Empty;
            StringBuilder builder = new StringBuilder();
            if (ancestors)
            {
                List<string> entities = new List<string>();
                do
                {
                    // The EntityType
                    builder.Append(entity.EntityType);

                    // The EntitySubType
                    if (!string.IsNullOrEmpty(entity.EntitySubType))
                    {
                        builder.Append("{");
                        builder.Append(entity.EntitySubType);
                        builder.Append("}");
                    }

                    // The Id
                    if (entity.Id != NoId)
                    {
                        builder.Append('#');
                        builder.Append(entity.Id.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    entity = entity.ParentEntity;
                    entities.Add(builder.ToString());
                    builder.Length = 0;
                }
                while (entity != null);

                for (int i = entities.Count - 1; i >= 0; i--)
                {
                    builder.Append("\\");
                    builder.Append(entities[i]);
                }
            }
            else
            {
                // The EntityType
                builder.Append(entity.EntityType);

                // The EntitySubType
                if (!string.IsNullOrEmpty(entity.EntitySubType))
                {
                    builder.Append("{");
                    builder.Append(entity.EntitySubType);
                    builder.Append("}");
                }

                // The Id
                if (entity.Id != NoId)
                    builder.Append(entity.Id.ToString(System.Globalization.CultureInfo.InvariantCulture));
            }
            return builder.ToString();
        }

        #endregion

        #region Parse

        /// <summary>
        /// Parses an Ancestor string into a list of Identifiable entities, where the first item is the bottommost parent,
        /// </summary>
        /// <param name="ancestryString"></param>
        /// <returns></returns>
        public static IIdentifiableEntity[] ParseAncestorString(string ancestryString)
        {
            string[] entityStrings = ancestryString.Split('\\');
            List<IIdentifiableEntity> identifiableEntityList = new List<IIdentifiableEntity>();
            IIdentifiableEntity currentParent = null;
            System.Text.RegularExpressions.Regex allowedEntityStringFormat = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\.]+({[a-zA-Z0-9_\.]+})?(#[0-9]+)?$");

            foreach (string entityString in entityStrings)
            {
                if (string.IsNullOrEmpty(entityString))
                    continue;

                if (!allowedEntityStringFormat.IsMatch(entityString))
                    return new IIdentifiableEntity[0];

                string entityType;
                string entitySubType = string.Empty;
                int id = NoId;

                //Entity string can have the following formats:
                // 1. Entity
                // 2. Entity{SubType}
                // 3. Entity{SubType}#Id
                // 4. Entity#Id

                string[] firstSplit = entityString.Split('#');
                if (firstSplit.Length >= 1)
                {
                    //Is it case 1 or 2?
                    List<string> secondSplit = new List<string>(firstSplit[0].Split('{', '}'));
                    while (secondSplit.Contains(string.Empty))
                        secondSplit.Remove(string.Empty);
                    if (secondSplit.Count == 1)
                    {
                        //Was Case 1
                        entityType = secondSplit[0];
                    }
                    else if (secondSplit.Count == 2)
                    {
                        //Was Case 2
                        entityType = secondSplit[0];
                        entitySubType = secondSplit[1];
                    }
                    else
                        return new IIdentifiableEntity[0];
                    if (firstSplit.Length == 2)
                        id = int.Parse(firstSplit[1], System.Globalization.CultureInfo.InvariantCulture);
                    else if (firstSplit.Length > 2)
                        return new IIdentifiableEntity[0];
                }
                else
                    return new IIdentifiableEntity[0];

                IIdentifiableEntity entity = new IdentifiableEntity(id, entityType, entitySubType, currentParent);
                identifiableEntityList.Add(entity);
                currentParent = entity;
            }
            return identifiableEntityList.ToArray();
        }

        /// <summary>
        /// Parses an ancestry string entity into an IdentifiableEntity object whith newly created Identifiable entities for parents.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static IIdentifiableEntity Parse(string path)
        {
            System.Text.RegularExpressions.Regex allowedEntityStringFormat = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\.]+({[a-zA-Z0-9_\.]+})?(#[0-9]+)?$");

            string[] entityStrings = path.TrimStart('\\').Split('\\');
            IdentifiableEntity currentParent = null;

            foreach (string entityString in entityStrings)
            {
                if (!allowedEntityStringFormat.IsMatch(entityString))
                    return null;

                string entityType;
                string entitySubType = string.Empty;
                int id = NoId;

                //Entity string can have the following formats:
                // 1. Entity
                // 2. Entity{SubType}
                // 3. Entity{SubType}#Id
                // 4. Entity#Id

                string[] firstSplit = entityString.Split('#');
                if (firstSplit.Length >= 1)
                {
                    //Is it case 1 or 2?
                    List<string> secondSplit = new List<string>(firstSplit[0].Split('{', '}'));
                    while (secondSplit.Contains(string.Empty))
                        secondSplit.Remove(string.Empty);
                    if (secondSplit.Count == 1)
                    {
                        //Was Case 1
                        entityType = secondSplit[0];
                    }
                    else if (secondSplit.Count == 2)
                    {
                        //Was Case 2
                        entityType = secondSplit[0];
                        entitySubType = secondSplit[1];
                    }
                    else
                        return null;
                    if (firstSplit.Length == 2)
                        id = int.Parse(firstSplit[1], System.Globalization.CultureInfo.InvariantCulture);
                    else if (firstSplit.Length > 2)
                        return null;
                }
                else
                    return null;
                IdentifiableEntity entity = new IdentifiableEntity(id, entityType, entitySubType, currentParent);
                currentParent = entity;
            }
            return currentParent;
        }

        #endregion
    }
}