using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FSI.Lib.Guis.SieTiaWinCCMsgMgt
{
    public class WinCC
    {
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);


        [DllImport("user32.dll")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll")]
        static extern IntPtr PostMessage(IntPtr hwndParent, int msg, int wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool IsWindowVisible(IntPtr hWnd);

        const int BM_CLICK = 0x00F5; //message for Click which is a constant
        const int WM_LBUTTONDOWN = 0x0201; //message for Mouse down
        const int WM_LBUTTONUP = 0x0202; // message for Mouse up
        
        private CancellationTokenSource tokenSource = null;
        private CancellationToken token;
        private Task task = null;

        private BackgroundWorker backgroundWorker;


        public bool AutoStart { get; set; }
        public int UpdateIntervall { get; set; }
        public string WindowsName { get; set; }
        public string WindowsClassName { get; set; }
        public string ButtonName { get; set; }

        public WinCC()
        {
            backgroundWorker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;

            if (AutoStart)
            {
                Start();
            }
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(UpdateIntervall);

                    // Find windos by Name
                    var windowHandle = FindWindow(WindowsClassName, WindowsName);

                    if (windowHandle != IntPtr.Zero && IsWindowVisible(windowHandle))
                    {
                        SetForegroundWindow(windowHandle);
                        var btnHandle = FindWindowEx(windowHandle, IntPtr.Zero, null, ButtonName);
                        SendMessage(btnHandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);                       
                    }
                }
            }
        }

        public void Start()
        {
            if (backgroundWorker.IsBusy != true)
            {
                backgroundWorker.RunWorkerAsync();
            }           
            Status = true;            
        }

        public void Stop()
        {
            if (backgroundWorker.WorkerSupportsCancellation == true)
            {
                backgroundWorker.CancelAsync();
            }
            Status = false;                        
        }
       
        public bool Status { get; set; }
        
        private void WinCCMsgMgt()
        {
            while (true)
            {
                try
                {
                    if (token.IsCancellationRequested)
                    {
                        token.ThrowIfCancellationRequested();
                    }
                    //MessageBox.Show("13456");
                    Thread.Sleep(5000);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            bool disposedValue = false;

            try
            {
                if (!disposedValue)
                {
                    if (disposing)
                    {
                        tokenSource.Cancel();
                        task.Wait();
                        tokenSource.Dispose();
                        task.Dispose();
                    }

                    disposedValue = true;
                }
            }
            catch
            {
            }
            finally
            {
                tokenSource = null;
                task = null;
            }
        }

    }
}
