using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WSPOSInitiative.Common
{
    /// <summary>
    /// ワーカスレッド保持
    /// ①OPOSドライバ実装のClaim管理メカニズムがスレッドベースである(ことが多い）
    /// ②WS-POSのメソッド呼び出しのスレッドはスレッドプールから都度割り当てられるため、
    /// 　同一コンシューマからの呼び出しが同一スレッドとは限らない
    /// ③異なるコンシューマからの呼び出しが異なるスレッドとは限らない
    /// このため、デバイス呼び出し用のスレッドを保持する
    /// Worker Thread Holder
    /// 1. The Claim management mechanism of OPOS driver mounting is a thread base. (In the cases of many) 
    /// 2. Since the thread of a method call of WS-POS is assigned from a thread pool as for a capital degree, 
    ///    the call from the same consumer is not necessarily the same thread. 
    /// 3. It is not necessarily a thread from which the call from a different consumer differs. 
    /// The thread for a device call is held for the above reason.
    /// </summary>
    public class WorkerThreadHolder : IDisposable
    {
        public const string LoopCoreThreadSlotName = "WSPOSInitiative.Common.WorkerThreadHolder.LoopCore";

        public delegate void TargetMethod();
        public delegate bool WorkerThreadCore();

        volatile bool disposed = false;

        volatile Thread workerThread = null;

        volatile IEventWait endExecWait = new EventWait();

        volatile Exception workerThreadException;

        volatile bool methodInProgress = false;

        volatile Queue<TargetMethod> targetMethodQueue = new Queue<TargetMethod>();


        public WorkerThreadHolder()
        {
            workerThread = new Thread(this.WorkerLoop);
            workerThread.IsBackground = false;//  Need for Message Queue
            workerThread.SetApartmentState(ApartmentState.STA);
            workerThread.Name = "WorkerThreadHolder";
            workerThread.Start();
        }

        public void Dispose()
        {
            disposed = true;
            endExecWait.Wait(Timeout.Infinite);
            endExecWait.Dispose();
        }

        void WorkerLoop()
        {
            try
            {
                while (true)
                {
                    if (WorkerLoopCore() == false)
                    {
                        return;
                    }
                }
            }
            finally
            {
                endExecWait.Signal();
            }
        }

        bool WorkerLoopCore()
        {
            Thread.Sleep(1);
            Application.DoEvents();

            if (disposed)
            {
                Thread.FreeNamedDataSlot(LoopCoreThreadSlotName);
                return false;
            }
            if (methodInProgress)
            {
                return true;
            }

            TargetMethod target = null;
            lock (targetMethodQueue)
            {
                if (targetMethodQueue.Count > 0)
                {
                    target = targetMethodQueue.Dequeue();
                }
            }
            try
            {
                if (target != null)
                {
                    methodInProgress = true;
                    target();
                    methodInProgress = false;
                    target = null;
                    Thread.SetData(Thread.GetNamedDataSlot(LoopCoreThreadSlotName), null);
                    endExecWait.Signal();
                }
            }
            catch (Exception ex)
            {
                methodInProgress = false;
                target = null;
                Thread.SetData(Thread.GetNamedDataSlot(LoopCoreThreadSlotName), null);
                workerThreadException = ex;
                endExecWait.Signal();
            }

            return true;
        }

        public void ExecuteOnWorkerThread(TargetMethod targetMethod)
        {
            workerThreadException = null;
            lock (targetMethodQueue)
            {
                Thread.SetData(Thread.GetNamedDataSlot(LoopCoreThreadSlotName), new WorkerThreadCore(WorkerLoopCore));
                targetMethodQueue.Enqueue(targetMethod);
            }

            endExecWait.Wait(Timeout.Infinite);

            if (workerThreadException != null)
            {
                if (workerThreadException is Microsoft.PointOfService.PosControlException)
                {
                    var pex = workerThreadException as Microsoft.PointOfService.PosControlException;
                    throw new Microsoft.PointOfService.PosControlException(pex.Message, pex.ErrorCode, pex.ErrorCodeExtended, pex);
                }
                else
                {
                    throw new Exception(workerThreadException.Message, workerThreadException);
                }
            }
        }
    }
}
