#region << Using Directives >>
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Volpe.Cafe.Utils;
#endregion

namespace Volpe.Cafe.EspressoUI.LegacyControls
{
    static class RecentItems
    {

        #region /*** Ctors ***/

        static RecentItems()
        {
            ItemsPath = ApplicationInfo.RecentListFilePath;
            Items = new List<string>(MaxItems);
            // load the recent list
            if (File.Exists(ItemsPath))
            {
                StreamReader reader = new StreamReader(ItemsPath);
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    Items.Add(line);
                    if (Items.Count == MaxItems) { break; }
                }
                reader.Close();
            }
        }

        #endregion

        #region /*** Methods ***/

        static void WriteRecentList(string lines, int retry)
        {
            try
            {
                FileStream writerStream = new FileStream(ItemsPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
                StreamWriter writer = new StreamWriter(writerStream);
                writer.Write(lines);
                writer.Close();
            }
            catch //(Exception ex)
            {
                if (retry == 0) { return; } // updating recent items list failed
                Thread.Sleep(125);
                WriteRecentList(lines, retry - 1);
            }
        }

        public static void AddEntry(string path)
        {
            // prevent duplicates
            int index = Items.IndexOf(path);
            if (index != -1) { Items.RemoveAt(index); }
            // check for overflow
            if (Items.Count == MaxItems) { Items.RemoveAt(0); }
            // add item
            Items.Add(path);
            // add to recent list
            string lines = "";
            for (int i = 0; i < Items.Count; i++) { lines += Items[i] + "\n"; }
            WriteRecentList(lines, 2);
        }
        public static string GetEntry(int index)
        {
            if (index < 0 || index >= Items.Count) { return null; }
            return Items[index];
        }
        public static string[] GetAllEntries()
        {
            return Items.ToArray();
        }

        #endregion

        #region /*** Variables ***/

        public const int MaxItems = 100;

        static readonly List<string> Items;
        static readonly string ItemsPath;

        #endregion

    }
}
