using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Net;

namespace SE290A_BackOfficeSim_CoreApi
{
    class DatabaseWatcher
    {
        private static Thread UpdateStatusThread;

        private static volatile bool running;
        private static volatile bool paused;

        private static int SqlUpdateIntervalStatusTables = 1;

        public static void Start()
        {
            running = true;
            paused = false;

            UpdateStatusThread = new Thread(new ThreadStart(DoUpdateStatus));
            UpdateStatusThread.Name = "UpdateStatusThread";
            UpdateStatusThread.Priority = ThreadPriority.Lowest;
            UpdateStatusThread.Start();
        }

        static void DoUpdateStatus()
        {
            while (running)
            {
                if (!paused)
                    DatabaseHelper.UpdateStatusTables();

                if (running)
                {
                    try
                    {
                        Thread.Sleep(SqlUpdateIntervalStatusTables * 1000 + 100);
                    }
                    catch (ThreadInterruptedException) { }
                }
            }
        }

        [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, ControlThread = true)]
        private static void KillThreads()
        {
            if (UpdateStatusThread != null)
                UpdateStatusThread.Join();
        }

        public static void Pause()
        {
            paused = true;

            int i = 0;

            while (UpdateStatusThread.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
            {
                Thread.Sleep(10);

                if (++i < 1000)
                    break;
            }
        }

        public static void Resume()
        {
            paused = false;
        }

        public static void Stop()
        {
            running = false;

            if (UpdateStatusThread != null)
            {
                UpdateStatusThread.Interrupt();

                int i = 0;

                while (UpdateStatusThread.IsAlive && ++i < 2000)
                    Thread.Sleep(10);
            }

            KillThreads();
        }
    }
}
