using System;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Themes;
using Pilz.Updating.UpdateInstaller.Lib;
using Pilz.Plugins.Advanced;
using Pilz.Updating.UpdateInstaller.AddOns;

namespace Pilz.Updating.UpdateInstaller
{
    public partial class Main
    {
        // C o n s t r u c t o r s

        public Main()
        {
            // G u i
            this.Shown += Main_Shown;
            this.FormClosed += Main_FormClosed;
            this.FormClosing += Main_FormClosing;

            // Get arguments
            var args = My.MyProject.Application.CommandLineArgs.ToArray();
            if (args.Any())
            {
                // Load config
                installer = new Lib.UpdateInstaller(UpdateInstallerConfig.Parse(args[0]));
                PluginFunctionController.Instance.ExecuteAll(UpdateInstallerFunctionTypes.OnInstancingUpdateInstaller);

                // Init Form
                InitializeComponent();

                // Init Style
                RadThemeComponentBase themeToUse = installer.Configuration.UIDarkMode ? new FluentDarkTheme() : new FluentTheme();
                ThemeResolutionService.ApplicationThemeName = themeToUse.ThemeName;

                // Init Application Header Text
                string header;
                if (!string.IsNullOrEmpty(installer.Configuration.ApplicationName))
                    header = string.Format(My.Resources.UpdateInstallerGuiLangRes.String_UpdatingApplicationX, installer.Configuration.ApplicationName);
                else
                    header = My.Resources.UpdateInstallerGuiLangRes.String_UpdateIsRunning;

                radLabel_Header.Text = $"<html><span style=\"font-size: 18pt; color: #b7472a\"><b>{header}</b></span></html>";
            }

            if (installer is null)
                Environment.Exit(0);
        }

        // F i e l d s

        private bool allowClose = false;
        private readonly Lib.UpdateInstaller installer;

        // F e a t u r e s

        private void SetStatus(UpdateInstallerStatus newStatus)
        {
            string newStatusText = string.Empty;
            Image newStatusImage = null;

            switch (newStatus)
            {
                case UpdateInstallerStatus.CopyingFiles:
                    newStatusText = My.Resources.UpdateInstallerGuiLangRes.Status_CopyingFiles;
                    break;
                case UpdateInstallerStatus.Done:
                    newStatusText = My.Resources.UpdateInstallerGuiLangRes.Status_Done;
                    break;
                case UpdateInstallerStatus.Extracting:
                    newStatusText = My.Resources.UpdateInstallerGuiLangRes.Status_Extracting;
                    break;
                case UpdateInstallerStatus.RemovingFiles:
                    newStatusText = My.Resources.UpdateInstallerGuiLangRes.Status_RemovingFiles;
                    break;
                case UpdateInstallerStatus.Waiting:
                    newStatusText = My.Resources.UpdateInstallerGuiLangRes.Status_Waiting;
                        break;
            }

            switch (newStatus)
            {
                case UpdateInstallerStatus.CopyingFiles:
                    newStatusImage = MyIcons.icons8_copy_16px;
                    break;
                case UpdateInstallerStatus.Extracting:
                    newStatusImage = MyIcons.icons8_open_archive_16px;
                    break;
                case UpdateInstallerStatus.RemovingFiles:
                    newStatusImage = MyIcons.icons8_recycle_bin_16px;
                    break;
                case UpdateInstallerStatus.Waiting:
                    newStatusImage = MyIcons.icons8_sand_timer_16px;
                    break;
                case UpdateInstallerStatus.Done:
                    newStatusImage = MyIcons.icons8_checkmark_16px;
                    break;
            }

            radLabel_Status.Text = newStatusText;
            radLabel_Status.Image = newStatusImage;

            //if (newStatus == UpdateInstallerStatus.Done)
            //{
            //    allowClose = true;
            //    Close();
            //}
        }

        private async Task WaitforHostApp()
        {
            SetStatus(UpdateInstallerStatus.Waiting);
            await Task.Run(() => installer.WaitForHostApplication());
        }

        private async void ExecuteUpdate()
        {
            await Task.Run(() => installer.InstallUpdate());
            allowClose = true;
            Close();
        }

        private async void Main_Shown(object sender, EventArgs e)
        {
            radWaitingBar1.StartWaiting();
            await WaitforHostApp();
            ExecuteUpdate();
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            installer.StartHostApplication();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            radWaitingBar1.StopWaiting();
            e.Cancel = !allowClose;
        }

        private void Installer_StatusChanges(object sender, UpdateInstallerStatusChangedEventArgs e)
        {
            base.Invoke(new Action(() => SetStatus(e.NewStatus)));
        }
    }
}