using System;
using System.Collections.Generic;

namespace ZionRobot.Tasks
{
    class Input
    {
        private bool running;
        private Handlers.Browser handler;
        private int limitTime = 960;//120;
        private System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

        public bool Running { get => this.running; }

        public Input()
        {
            this.running = false;
        }

        public void Execute(Models.Source.Origin source) //Models.Process.Workflow workflow)
        {
            if (!running /*&& Helpers.Shift.isDuringTheWeek(DateTime.Now)*/)
            {
                running = true;
                stopwatch.Start();

                System.Windows.Application.Current.Dispatcher.Invoke((System.Action)delegate
                {
                    this.handler = Handlers.Browser.Instance;
                });

                new System.Threading.Thread(() =>
                {
                    System.Threading.Thread t = new System.Threading.Thread(() =>
                    {
                        string outputFolder = System.IO.Path.Combine(
                            Persistence.Basic.SearchResultFolder,
                            source.OutputFolder,
                            DateTime.Now.ToString("yyyyMMdd"));

                        System.Windows.Application.Current.Dispatcher.Invoke((System.Action)delegate
                        {
                            handler.Source = source;
                            handler.ExecuteAndSave(outputFolder);
                        });

                    });

                    t.Start();

                    new System.Threading.Thread(() => {

                        while (handler.Main == null || handler.Main.IsAlive)
                        {
                            if (stopwatch.Elapsed.TotalSeconds > limitTime)
                                break;

                            System.Threading.Thread.Sleep(1000);
                        }

                        stopwatch.Stop();
                        stopwatch.Reset();

                        System.Windows.Application.Current.Dispatcher.Invoke((System.Action)delegate
                        {
                            handler.Close();
                        });

                        running = false;

                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        GC.Collect();
                    }).Start();

                }).Start();
            }
        }
    }
}
