#region << Using Directives >>
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Volpe.Cafe.Utils;
#endregion
namespace Volpe.Cafe.UI
{
    static class RecentItems
    {
        #region 
        static RecentItems()
        {
            ItemsPath = ApplicationInfo.RecentListFilePath;
            Items = new List<string>(MaxItems);
            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 
        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 
            {
                if (retry == 0) { return; } 
                Thread.Sleep(125);
                WriteRecentList(lines, retry - 1);
            }
        }
        public static void AddEntry(string path)
        {
            int index = Items.IndexOf(path);
            if (index != -1) { Items.RemoveAt(index); }
            if (Items.Count == MaxItems) { Items.RemoveAt(0); }
            Items.Add(path);
            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 
        public const int MaxItems = 100;
        static readonly List<string> Items;
        static readonly string ItemsPath;
        #endregion
    }
}

