using System.Collections.Specialized;
using System.IO;
using NotepadEnhanced.AppState;

namespace NotepadEnhanced.Helpers
{
    static class RecentFileQue
    {
        /// <summary>
        /// The string collection is null sometimes, it may need to be instantiated
        /// This needs to be called before the list can be used to avoid errors
        /// </summary>
        public static void Initialize()
        {
            if (UserSettings.Instance.RecentFiles == null)
            {
                UserSettings.Instance.RecentFiles = new StringCollection();
            }
            else
            {
                RemoveNonExistentRecentItems();
            }
        }

        private static void RemoveNonExistentRecentItems()
        {
            for (int i = 0; i < UserSettings.Instance.RecentFiles.Count; i++)
            {
                string fileName = UserSettings.Instance.RecentFiles[i];

                if (!File.Exists(fileName))
                {
                    UserSettings.Instance.RecentFiles.RemoveAt(i);
                }
            }
        }

        public static void AddFiles(params string[] filenames)
        {
            foreach (string name in filenames)
            {
                // If the file is already listed, remove it then add it again
                if (!IsNewFile(name))
                {
                    UserSettings.Instance.RecentFiles.Remove(name);
                }

                // Add it again so it is recent
                UserSettings.Instance.RecentFiles.Add(name);
            }

            LimitQue();
        }

        /// <summary>
        /// This will allow us to treat the stringCollection as a que
        /// </summary>
        public static void LimitQue()
        {
            while (UserSettings.Instance.RecentFiles.Count > UserSettings.Instance.RecentQueSize)
            {
                UserSettings.Instance.RecentFiles.RemoveAt(0);
            }
        }

        private static bool IsNewFile(string fileName)
        {
            for (int i = 0; i < UserSettings.Instance.RecentFiles.Count; i++)
            {
                if (fileName == UserSettings.Instance.RecentFiles[i])
                {
                    return false;
                }
            }

            return true;
        }

        public static void ClearRecentList()
        {
            UserSettings.Instance.RecentFiles.Clear();
        }

        public static StringCollection FileNames
        {
            get { return UserSettings.Instance.RecentFiles.Reverse();  }
        }
    }
}
