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

namespace DALI.Toolkit.Utils
{
    public class VerticesName
    {
        private SortedDictionary<NamePoint, int> _names;

        public static VerticesName _instance = null;

        public static VerticesName Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new VerticesName()
                    {
                        _names = new SortedDictionary<NamePoint, int>(new SortNamePointComparer())
                    };

                }

                return _instance;
            }
        }

        public VerticesName()
        {
        }

        public string GetNextNamePoint(bool addNextName)
        {
            if (_names.Count == 0)
            {
                NamePoint first = new NamePoint("A");

                if (addNextName)
                {
                    _names.Add(first, 1);
                }

                return first.ToString();
            }
            else
            {
                var last = _names.Last().Key;
                NamePoint nextName = last.GetNextName();

                if (addNextName)
                {
                    _names.Add(nextName, 1);
                }

                return nextName.ToString();
            }
        }

        public void AddName(string name)
        {
            NamePoint n = new NamePoint(name);

            if (_names.ContainsKey(n))
            {
                var newCountName = _names[n];
                newCountName++;

                _names[n] = newCountName;
            }
            else
            {
                _names.Add(n, 1);
            }
        }

        public void AddNameSubSegment(string name)
        {
            NamePoint n = new NamePoint(name);

            if (_names.ContainsKey(n))
            {
            }
            else
            {
                _names.Add(n, 1);
            }
        }

        public void RemoveName(string name)
        {
            NamePoint n = new NamePoint(name);

            if (_names.ContainsKey(n))
            {
                var countName = _names[n];
                countName--;

                if (countName == 0)
                {
                    _names.Remove(n);
                }
            }
        }

        public void ResetCounter()
        {
            _names.Clear();
        }
    }

    public class SortNamePointComparer : IComparer<NamePoint>
    {
        public int Compare(NamePoint n1, NamePoint n2)
        {
            if(n1.NameIsStrictUpTo(n2))
            {
                return 1;
            }
            else if(n1.Equals(n2))
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }
}
