using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Yaulw.WPF;
using System.Reflection;
using System.Diagnostics;
using System.IO;

namespace MSLMobile
{
    /// <summary>
    /// Interaction logic for HiddenMainWindow.xaml
    /// </summary>
    public partial class HiddenMainWindow : Window
    {

        // Hard-coded in * Registry Strings / Settings
        internal const string LOCAL_MACHINE_SUBKEY = "Software\\MSLMobile";
        internal const string LOCAL_MACHINE_INITIALSETUPDT = "InitialSetup";

        KeepHidden _keepHidden = null;
        Yaulw.File.LoggerQuick log = null;

        public HiddenMainWindow()
        {            
            InitializeComponent();
            _keepHidden = new KeepHidden(this);

            // Create Log File in Temp Path
            string temppath = System.IO.Path.GetTempPath();
            log = new Yaulw.File.LoggerQuick("MSLMobile", true, temppath);

            // * LASTLY * Now show The windows
            _keepHidden.Show();                       
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {            
            const string SERVICE_NAME = "McKesson MSL Mobile Api Server";
            const string FOLDER_NAME = "McKesson Mobile Api";
            string Result = "";
            log.Info("***** Setup for '{0}' started at '{1}' *****", SERVICE_NAME, DateTime.Now.ToString());

            // Stop the service if it exists
            bool bSuccess = Yaulw.Installer.Common.StopService(SERVICE_NAME, 120);
            if (bSuccess)
                log.Info("Stopping {0} Succeeded", SERVICE_NAME);
            else
                log.Info("Stopping {0} Failed", SERVICE_NAME);
                        
            // Make sure to kill all instances of DiagnoseMobile.exe (We will update it)
            Process[] diagnoseMobiles = Yaulw.Process.ProcessW.AllRunningProcessesOf("DiagnoseMobile");
            foreach (Process p in diagnoseMobiles)
            {
                log.Info("Killing Diagnose Mobile .exe PID:{0}", p.Id );
                bSuccess = Yaulw.Process.PStarter.KillProcess((uint)p.Id, false, 10, false, 0);
                if(bSuccess)
                    log.Info("Killing Diagnose Mobile Succeeded .exe PID:{0}", p.Id);
                else
                    log.Error("Killing Diagnose Mobile Failed .exe PID:{0}", p.Id);
            }

            // Get DestPath
            string ProgramFiles = Yaulw.Installer.Common.GetProgramFilesPathOnSystemWithEndSlash();
            string DestPath = ProgramFiles + FOLDER_NAME;
            if (!System.IO.Directory.Exists(DestPath))
            {
                log.Info("Creating Directory '{0}'", DestPath);
                System.IO.Directory.CreateDirectory(DestPath);
            }
            else
            {
                // Delete as many files as possible (do a whole new Setup!) (try a from scratch re-install)                                
                System.IO.DirectoryInfo dI = new DirectoryInfo(DestPath);
                foreach (FileInfo fI in dI.GetFiles())
                {
                    try { fI.Delete(); log.Info("Deleting File '{0}' succeeded", fI.Name); }
                    catch (Exception) { log.Error("Deleting File '{0}' failed", fI.Name); }
                }
            }

            // Extract All Resources to corresponding Programs Folder
            string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            foreach (string s in resources)
            {
                int nIndex = s.IndexOf("Components.");
                if (nIndex != -1)
                {
                    var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(s);
                    if (stream != null)
                    {
                        // Extract the File
                        string FileName = s.Substring(nIndex + "Components.".Length);
                        string FileNameNPath = DestPath + "\\" + FileName;
                        bSuccess = Yaulw.Installer.Common.ExtractResourceStreamToFile(stream, FileNameNPath, true);
                        if(bSuccess)
                            log.Info("Extracting Resource '{0}' succeeded", s);
                        else
                            log.Info("Extracting Resource '{0}' failed", s);
                    }
                }
            }

            // Install the Service
            bool bServiceExists = Yaulw.Installer.Common.ServiceExists(SERVICE_NAME);
            if (!bServiceExists)
            {
                log.Info("Service {0} does not exist", SERVICE_NAME);
                string InstallUtil = Yaulw.Installer.Common.GetNetFrameworkUtilFileNameNPathFile("installutil.exe");
                if (!String.IsNullOrEmpty(InstallUtil))
                {
                    Result = Yaulw.Installer.Common.RunCmdLine(InstallUtil + " \"" + (DestPath + "\\" + "PlutoServer.MSL.exe") + "\" /LogToConsole=true /LogFile=");
                    if (Result.Contains("failed"))
                    {
                        log.Error("Service Install Error:");
                        log.Error(Result);
                    }
                    else
                    {
                        log.Info("Service Install Success:");
                        log.Info(Result);
                    }
                }
            }
            else
            {
                log.Info("Service {0} already exists", SERVICE_NAME);
            }

            // Open everything needed for Windows Firewall
            // http://stackoverflow.com/questions/7701667/how-to-add-outbound-windows-firewall-exception
            // http://www.rickwargo.com/2011/01/08/port-forwarding-port-mapping-on-windows-server-2008-r2/
            // http://support.microsoft.com/kb/947709
            Result = Yaulw.Installer.Common.RunCmdLine(String.Format("netsh firewall add allowedprogram \"{0}\" \"{1}\" ENABLE ALL", (DestPath + "\\" + "PlutoServer.MSL.exe"), "Pluto.MSL.Mobile"));
            bSuccess = Result.Contains("successfully") || Result.Contains("Ok.") || Result.Contains("The service has not been started");
            if(bSuccess)
               log.Info("Adding Firewall Rule1 Success:{0}", Result);
            else
               log.Error("Adding Firewall Rule1 Error:{0}", Result);
            
            Result = Yaulw.Installer.Common.RunCmdLine(String.Format("netsh firewall add allowedprogram \"{0}\" \"{1}\" ENABLE ALL", (DestPath + "\\" + "DiagnoseMobile.exe"), "DiagnoseMobile"));
            bSuccess = Result.Contains("successfully") || Result.Contains("Ok.") || Result.Contains("The service has not been started");
            if (bSuccess)
                log.Info("Adding Firewall Rule2 Success:{0}", Result);
            else
                log.Error("Adding Firewall Rule2 Error:{0}", Result);
            
            Result = Yaulw.Installer.Common.RunCmdLine("netsh firewall set portopening tcp 1945 Pluto.MSL.Mobile ENABLE ALL");
            bSuccess = Result.Contains("successfully") || Result.Contains("Ok.") || Result.Contains("The service has not been started");
            if (bSuccess)
                log.Info("Adding Firewall Rule3 Success:{0}", Result);
            else
                log.Error("Adding Firewall Rule3 Error:{0}", Result);
            
            // Create a shortcut to diagnose mobile in the Start Menu            
            string DiagnoseMobileExe = DestPath + "\\" + "DiagnoseMobile.exe";
            string StartMenu = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
            // Delete the shortcut without a space in it (ugly without a space)
            if(File.Exists(StartMenu + "\\" + "DiagnoseMobile.lnk"))
               File.Delete(StartMenu + "\\" + "DiagnoseMobile.lnk");
            // Create it with a space
            Yaulw.Installer.Common.CreateFileShortcut(DiagnoseMobileExe, StartMenu + "\\" + "Diagnose Mobile.lnk");

            // Set the Initial Setup DT for the service, so that it knows NOT to auto-update upon
            // first launch (this could be something Medisoft/Lytec setup related not just the setup.exe)
            // ~let's avoid trying to update during the initial setup alltogether
            Yaulw.Registry.RegKey.SetKey<DateTime>(Yaulw.Registry.HKEYRoot.LocalMachine, LOCAL_MACHINE_SUBKEY, LOCAL_MACHINE_INITIALSETUPDT, DateTime.Now);

            // Start the Service, when done
            bSuccess = Yaulw.Installer.Common.StartService(SERVICE_NAME);
            if (bSuccess)
                log.Info("Starting {0} Succeeded", SERVICE_NAME);
            else
                log.Info("Starting {0} Failed", SERVICE_NAME);

            // Close this window, setup is done...
            //this.Close();
            Application.Current.Shutdown();
        }

    }
}
