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
    {

        KeepHidden _keepHidden = null; 
        public HiddenMainWindow()
        {            
            InitializeComponent();
            _keepHidden = new KeepHidden(this);
            _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 = "";
            
            // Stop the service if it exists
            Yaulw.Installer.Common.StopService(SERVICE_NAME, 30);

            // 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)
                     Yaulw.Process.PStarter.KillProcess((uint) p.Id, false, 10, false, 0);

            // Get DestPath
            string ProgramFiles = Yaulw.Installer.Common.GetProgramFilesPathOnSystemWithEndSlash();
            string DestPath = ProgramFiles + FOLDER_NAME;
            if (!System.IO.Directory.Exists(DestPath))
            {
                System.IO.Directory.CreateDirectory(DestPath);
            }
            else
            {
                // Delete the whole on a new Setup! (from scratch re-install) - not done in Mini Setup
                //Directory.Delete(DestPath);
                //System.IO.Directory.CreateDirectory(DestPath);
            }

            // 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;
                        Yaulw.Installer.Common.ExtractResourceStreamToFile(stream, FileNameNPath, true);
                    }
                }
            }

            // Install the Service
            bool bServiceExists = Yaulw.Installer.Common.ServiceExists(SERVICE_NAME);
            if (!bServiceExists)
            {
                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"))
                    //{                    
                    //}
                }
            }

            // 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"));
            Result = Yaulw.Installer.Common.RunCmdLine(String.Format("netsh firewall add allowedprogram \"{0}\" \"{1}\" ENABLE ALL", (DestPath + "\\" + "DiagnoseMobile.exe"), "DiagnoseMobile"));
            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");            

            // 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");

            // Start the Service, when done
            Yaulw.Installer.Common.StartService(SERVICE_NAME);

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

    }
}
