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

namespace nispi.Controls.Main.ThreadList.AutoReload
{
    class AutoReload
    {
        public AutoReload()
        {
        }

        public void MyThreadStart()
        {
            Thread t = new Thread(new ThreadStart(ReloadThread));
            t.IsBackground = true;
            t.Start();
        }

        public void ReloadThread()
        {
            List<string> reloadAddress;
            List<ThreadViewCommon> threadViewList;
            while (true)
            {
                for (int x = 0; x < 100; x += 1)
                {
                    int sleepTime = AutoReloadDataManager.GetTime();

                    int sleepTimePiece = sleepTime / 100;

                    Thread.Sleep(sleepTimePiece);
                }

                reloadAddress = AutoReloadDataManager.Get();

                threadViewList = MainFormConst.threadListTabMain.GetViewList();

                foreach (ThreadViewCommon tvc in threadViewList)
                {
                    try
                    {
                        int num = reloadAddress.FindIndex(a => a.Equals(tvc.datUrl) == true);
                        if (num == -1)
                            continue;
                        tvc.Reload();
                    }
                    catch { ;}
                }
            }
        }
    }

    class AutoReloadDataManager
    {
        public static List<string> reloadAddress = new List<string>();
        public static int sleepTime = 15000;
        public static Mutex mutex = new Mutex(false, "AutoReloadDataManager");


        public static void Add(string address)
        {
            mutex.WaitOne();

            try
            {
                if (0 < reloadAddress.FindIndex(a => a.Equals(address) == true))
                {
                    mutex.ReleaseMutex();
                    return;
                }

                reloadAddress.Add(address);
            }
            catch { ;}

            mutex.ReleaseMutex();
        }
        public static List<string> Get()
        {
            List<string> temp;

            mutex.WaitOne();

            temp = reloadAddress.ToList();

            mutex.ReleaseMutex();

            return temp;
        }
        public static void Remove(string address)
        {
            mutex.WaitOne();

            reloadAddress.Remove(address);

            mutex.ReleaseMutex();
        }

        public static int GetTime()
        {
            int time = 0;

            mutex.WaitOne();
            int temp = 0;
            if (true == Int32.TryParse(Const.form.optionMainForm.otherOption.AutoReloadTime,out temp))
                time = 1000*temp;
            else
                time = 15000;

            mutex.ReleaseMutex();

            return time;
        }
    }
}
