using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Input;
using Valg.EVA.Skanning.Signing;

namespace Valg.EVA.Skanning.JobManagement.Startup
{
    public class BuypassBootstrapper : IBuypassBootstrapper
    {
        private readonly ISignatureCryptographicServiceProvider cryptographicServiceProvider;
        private const string buypassAccessIidPath = @"Buypass Access\iid.exe";

        public BuypassBootstrapper(ISignatureCryptographicServiceProvider cryptographicServiceProvider)
        {
            this.cryptographicServiceProvider = cryptographicServiceProvider;
        }

        public void AttemptRestartBuypassMiddleware()
        {
            var pathToBuypass = AttemptGetPathToBuypass();

            if (File.Exists(pathToBuypass))
            {
                try
                {
                    Mouse.OverrideCursor = Cursors.Wait;

                    var processes = GetBuypassProcesses();
                    foreach (var process in processes)
                    {
                        try
                        {
                            process.Kill();
                            process.WaitForExit(3000);
                        }
                        catch (Exception)
                        {
                            
                        }
                    }

                    Process.Start(pathToBuypass); 

                    var waitForServiceToGetReadyCounter = 0;
                    while (!cryptographicServiceProvider.IsServiceReadyToSign() && waitForServiceToGetReadyCounter < 10)
                    {
                        waitForServiceToGetReadyCounter ++;
                        Thread.Sleep(500);
                    }
                }
                catch (Exception)
                {
                    
                    
                }
                finally
                {
                    Mouse.OverrideCursor = null;
                }
            }
        }

        
        
        
        
        private static IEnumerable<Process> GetBuypassProcesses()
        {
            return Process.GetProcessesByName("iid");
        }

        private static string AttemptGetPathToBuypass()
        {
            var pathToBuypass = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), buypassAccessIidPath);

            if (!File.Exists(pathToBuypass))
            {
                pathToBuypass = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), buypassAccessIidPath);
            }

            return pathToBuypass;
        }

        public static bool OneIidProcessIsRunning()
        {
            var processesByName = Process.GetProcessesByName("iid");
            return processesByName.Length == 1;
        }
    }
}
