using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GlobalScope;
using System.IO;

namespace Installer
{
    public partial class Installer : Form
    {

        private List<String> _Messages = new List<string>();


        public String FileNameExceptionContent
        {
            get
            {
                // Returns part of exec name to scan for and ignore in deleting and copying
                System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
                string exe = System.IO.Path.GetFullPath(ass.Location);
                string name = new FileInfo(exe).Name;
                string ext = new FileInfo(exe).Extension;
                name = name.Replace(ext, "");
                return name.ToLower();
            }
        }


        public Installer()
        {
            InitializeComponent();
        }

        private void Installer_Load(object sender, EventArgs e)
        {

            this.Text = Globals.SoftwareDescription + " installer";

            // Center screen
            this.Location = new Point((int)Math.Round((Screen.PrimaryScreen.Bounds.Width - this.Size.Width) / 2.0), (int)Math.Round((Screen.PrimaryScreen.Bounds.Height - this.Size.Height) / 2.0));


            // Running locally?
            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
            string exe = System.IO.Path.GetFullPath(ass.Location);



            if (!exe.ToLower().Contains(Globals.PathToServerVersion.ToLower()))
            {
                MessageBox.Show("You can only run " + Globals.SoftwareDescription + " from server!", Globals.SoftwareDescription, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            txtbFolder.Text = Globals.PathToPreferredInstall+@"\";

        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            fbd.RootFolder = Environment.SpecialFolder.Desktop;
            DialogResult dr = fbd.ShowDialog();

            if (dr != System.Windows.Forms.DialogResult.OK)
                return;

            txtbFolder.Text = fbd.SelectedPath;


        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string targetFolder = txtbFolder.Text + "\\";

            


            // Exists?
            if (!Directory.Exists(targetFolder))
            {
                DialogResult dr =                MessageBox.Show("Folder does not exist!\n\nDo you want to create the folder?", Globals.SoftwareDescription, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if( dr != System.Windows.Forms.DialogResult.Yes)
                    return;

                try
                {
                    Directory.CreateDirectory(targetFolder);
                }
                catch
                {
                    MessageBox.Show("Could not create folder!", Globals.SoftwareDescription, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            // Is empty folder?
            if (Directory.GetFiles(targetFolder).Length > 0)
            {
                MessageBox.Show("Installation folder must be empty!", Globals.SoftwareDescription, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            lbox.Location = new Point(18, 18);
            lbox.Visible = true;


            // Make fileLists
            string[] serverFileList;
            if (Directory.Exists(Globals.PathToServerVersion))
                serverFileList = Directory.GetFiles(Globals.PathToServerVersion);
            else
            {
                _Messages.Add("Serverpath not accessible!");
                UpdateMessages();
                return;
            }

            Boolean ErrorEncountered = false;

            // Copy all files except installer
            #region Copy to local
            foreach (string serverFilePath in serverFileList)
            {
                if (serverFilePath.ToLower().IndexOf(FileNameExceptionContent) < 0)
                {
                    string targetFilePath = "";
                    try
                    {
                        string name = new FileInfo(serverFilePath).Name;

                        targetFilePath = targetFolder + name;

                       
                            File.Copy(serverFilePath, targetFilePath, true);
                            _Messages.Add(String.Format("Copying : {0}\n", targetFilePath));
                        
                    }
                    catch (Exception ex)
                    {
                        ErrorEncountered = true;
                        _Messages.Add(String.Format("Failed to copy : {0}", targetFilePath));
                        _Messages.Add(String.Format("    [{0}]", ex.Message));
                    }
                    UpdateMessages();
                }
            }
            #endregion Copy to local


            Globals.RegisterUser(Globals.UpdaterModuleDescription + " (v" + Globals.BuildVersion + ")");

            _Messages.Add("User register updated");
            UpdateMessages();



            #region Create shortcut
                try
                {
                    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                    string shortcutLocation = Path.Combine(deskDir, Globals.SoftwareDescription + ".lnk");

                    if (File.Exists(shortcutLocation))
                        File.Delete(shortcutLocation);

                    IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
                    IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutLocation);

                    shortcut.Description = Globals.SoftwareDescription;
                    shortcut.IconLocation = targetFolder + Globals.FileNameOfSoftware;
                    shortcut.TargetPath = targetFolder + Globals.FileNameOfSoftware;
                    shortcut.Save();
                    _Messages.Add("Shortcut created");
                }
                catch (Exception ex)
                {
                    ErrorEncountered = true;
                    _Messages.Add("Failed to create shortcut :");
                    _Messages.Add(String.Format("    [{0}]", ex.Message));
                }
                finally
                {
                    UpdateMessages();
                }
            #endregion Create shortcut




            // Launch
           try
            {
                string f = targetFolder + Globals.FileNameOfSoftware;
                System.Diagnostics.Process.Start(f);
            }
            catch (Exception ex)
            {
                ErrorEncountered = true;
                _Messages.Add(String.Format("Failed to launch {0}", Globals.FileNameOfSoftware));
                _Messages.Add(String.Format("    [{0}]", ex.Message));
            }
            finally
            {
                if (!ErrorEncountered)
                    Application.Exit();
            }

        }



        private void UpdateMessages()
        {
            int stop = _Messages.Count - 1;
            int start = (int)Math.Max(stop - 19, 0);

            lbox.Items.Clear();

            for (int i = start; i <= stop; i++)
                lbox.Items.Add(_Messages[i]);

            lbox.Refresh();
            lbox.ClearSelected();
            this.Refresh();
            System.Threading.Thread.Sleep(50);
        }
    }
}
