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.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 Mobile Gateway Server";
            const string FOLDER_NAME = "McKesson Mobile Gateway";
            string Result = "";
            
            // Stop the service if it exists
            Yaulw.Installer.Common.StopService(SERVICE_NAME, 120);

            // Get DestPath
            //string ProgramFiles = Yaulw.Installer.Common.GetProgramFilesPathOnSystemWithEndSlash();
            string ProgramFiles = @"D:\";
            string DestPath = ProgramFiles + FOLDER_NAME;
            if (!System.IO.Directory.Exists(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;
                        bool bForceRewrite = !FileName.ToLower().EndsWith(".config");
                        if (!bForceRewrite && File.Exists(FileNameNPath))
                        {
                            MessageBoxResult result = MessageBox.Show(String.Format("Would you like to overwrite the following file '{0}' with the default installation File?", FileNameNPath), "Overwrite File?", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            bForceRewrite = (result == MessageBoxResult.Yes);
                            if (bForceRewrite) // Make a backup copy
                                File.Copy(FileNameNPath, FileNameNPath + ".bak");
                        }
                        Yaulw.Installer.Common.ExtractResourceStreamToFile(stream, FileNameNPath, bForceRewrite);
                    }
                }
            }

            // 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 + "\\" + "Pluto.RegistrationServer.exe") + "\"");
                    //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 + "\\" + "Pluto.RegistrationServer.exe"), "Pluto.RegistrationServer.exe"));
            Result = Yaulw.Installer.Common.RunCmdLine("netsh firewall set portopening tcp 443 Pluto.RegistrationServer.exe ENABLE ALL");
            //bSuccess = Result.Contains("successfully") || result.Contains("Ok.") || result.Contains("The service has not been started");            

            // Dont' Start the Service automatically, because maybe the DB Still needs to be configured
            // via the app.config file

            // Start the Service, when done? - Allow user to specify, there could be db changes, which will crash the
            // service so why auto-start it.         
            MessageBoxResult result2 = MessageBox.Show("Installation Done. Would you like to try to start the service?", "Install Complete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if(result2 == MessageBoxResult.Yes)
                Yaulw.Installer.Common.StartService(SERVICE_NAME);

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

    }
}
