using System;
using System.Diagnostics;
using System.IO;

namespace Valg.EVA.Skanning.Tools
{
    
    
    
    public class LocalDbToolProxy
    {
        private readonly string targetInstanceName;

        
        
        public LocalDbToolProxy(string targetInstanceName)
        {
            this.targetInstanceName = "\"" + targetInstanceName + "\"";
        }

        
        
        
        
        
        
        private static string GetCorrectPathToTool()
        {
			string[] programfilesDirectories = {@"c:\programfiler",@"c:\programfiler (x86)", @"c:\program files", @"c:\program files (x86)" };
	        foreach (var programfilesDirectory in programfilesDirectories)
	        {
		        var fullPath = GetFileNameOfLocalDbManagementTool(programfilesDirectory);

				if (File.Exists(fullPath))
				{
					return fullPath;
				}
	        }
	        throw new FileNotFoundException("Could not locate LocalDB admin utility. Verify that LocalDB is installed.");
        }

        private static string GetFileNameOfLocalDbManagementTool(string programFilesDir)
        {
            return Path.Combine(programFilesDir, @"Microsoft SQL Server\120\Tools\Binn\SqlLocalDB.exe");
        }

        public class InstanceRunningResult
        {
            public bool IsRunning { get; set; }
            public bool InstanceDoesNotExist { get; set; }
        }

        private void DeleteInstance()
        {
            ExecuteLocalDbToolCommand("d");
        }

        private void StopInstance()
        {
            ExecuteLocalDbToolCommand("p");
        }

        public string GetInstanceInfo()
        {
            return ExecuteLocalDbToolCommand("i");
        }

        private void StartInstance()
        {
            var output = ExecuteLocalDbToolCommand("s");
            if (!output.Contains("instance") && !output.Contains("started"))
            {
                throw new InvalidOperationException("Was not able to start ReadSoftFormsInstance localdb instance");
            }
        }

        private string ExecuteLocalDbToolCommand(string localDbToolCommand)
        {
            var toolPath = GetCorrectPathToTool();

            var processStartInfo = new ProcessStartInfo(toolPath);
            processStartInfo.Arguments = string.Format("{0} {1}", localDbToolCommand, targetInstanceName);
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.CreateNoWindow = true;
            var process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();

            var output = process.StandardOutput.ReadToEnd();

            process.WaitForExit();
            return output;
        }

        public InstanceRunningResult IsInstanceRunning()
        {
            var result = new InstanceRunningResult { IsRunning = false, InstanceDoesNotExist = false };

            var output = ExecuteLocalDbToolCommand("i");

            if (output.Contains("Running") && output.Contains("State"))
            {
                result.IsRunning = true;
            }
            else if (output.Contains("instance") && output.Contains("doesn't exist"))
            {
                result.InstanceDoesNotExist = true;
            }

            Debug.WriteLine(output);
            return result;
        }

        public void RecreateDatabaseInstance()
        {
            StopInstance();
            DeleteInstance();

            CreateInstance();
            StartInstance();
        }

        private void CreateInstance()
        {
            var output = ExecuteLocalDbToolCommand("c");
            if (!(output.Contains("instance") && output.Contains("created")))
            {
                throw new InvalidOperationException($"Was not able to create { targetInstanceName } localdb instance");
            }
        }
    }
}
