// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2022, Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using Hiperscan.ApoIdentCore.ActionControl;
using Hiperscan.ApoIdentCore.GuiControl;
using Hiperscan.ApoIdentCore.SoftwareUpgrade;
using Hiperscan.ApoIdentCommon;
using Hiperscan.ApoIdentCommon.ApoConfig;
using Hiperscan.GuiExtensions.Dialog;
using Hiperscan.Unix;

namespace Hiperscan.ApoIdentCore
{
    public partial class AppControl
    {
        public void CheckForPendingUpgrades(bool can_upgrade)
        {
            if (ApoIdentExecutionModeRecognizer.GetMode() == ApoIdentExecutionMode.Windows)
                this.StartAutomaticSoftwareLauncherWindows(can_upgrade);
        }

        public void LookForSoftwareUpgrade(bool can_upgrade)
        {
            this.ProgramSync.EnterCriticialZone();

            switch (ApoIdentExecutionModeRecognizer.GetMode())
            {
                case ApoIdentExecutionMode.Windows:
                    this.SoftwareUpgradeSettings.CanUpgrade = can_upgrade;
                    this.SearchForNewSoftwareWindows(this.SoftwareUpgradeSettings, false);
                    break;

                case ApoIdentExecutionMode.RaspianStandAlone:
                    SoftwareUpgradeRaspian upgrader = new SoftwareUpgradeRaspian(can_upgrade);
                    upgrader.OnError += this.OnRaspianError;
                    upgrader.Run();
                    break;

                default:
                    break;
            }

            this.ProgramSync.LeaveCriticalZone();
        }

        private void OnRaspianError(object sender, EventArgs e)
        {
            SoftwareUpgradeRaspian upgrader = sender as SoftwareUpgradeRaspian;

            UpdateArgs arg = new UpdateArgs();
            arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
            arg.DialogArgs.Exception = upgrader.Exception;
            arg.DialogArgs.Message = String.Format(Catalog.GetString("Cannot start update process: {0}"),
                                           upgrader.Exception.Message);

            this.UpdateGuiNeeded?.Invoke(arg);
        }

        private void StartAutomaticSoftwareLauncherWindows(bool can_upgrade)
        {
            this.SoftwareUpgradeSettings.CanUpgrade = can_upgrade;
            this.SearchForNewSoftwareWindows(this.SoftwareUpgradeSettings, true);
        }

        private void SearchForNewSoftwareWindows(SoftwareUpgradeSettings settings, bool is_automatic)
        {
            DateTime start_execution_time = DateTime.Now;

            SoftwareUpgradeWindows upgrader = new SoftwareUpgradeWindows(settings, is_automatic);

            bool new_upgrades = upgrader.SearchForUpgrades();

            if (new_upgrades)
                this.ShowUpgradeMessageDialog(upgrader, is_automatic);
            else
                this.ShowNoUpgradeMessageDialog(is_automatic);

            if (is_automatic)
                upgrader.DownloadUpgrades();

            Console.WriteLine("Software upgrader execution time: {0}",
                              (DateTime.Now - start_execution_time).TotalMilliseconds);
        }

        private void ShowUpgradeMessageDialog(SoftwareUpgradeWindows upgrader, bool is_automatic)
        {
            UpdateArgs arg = new UpdateArgs();
            arg.DialogArgs.StandardDialogType = StandardDialogType.Question;
            arg.DialogArgs.Message = Catalog.GetString(@"There are upgrades available:

");

            bool has_text = false;
            int count = 0;

            if (String.IsNullOrEmpty(upgrader.AvailableQuickStepUpgrade) == false)
            {
                arg.DialogArgs.Message += String.Format(Catalog.GetString(@"	- QuickStep Apo-Ident {0}
	  (program optimisation / bugfix release)"),
                                                        upgrader.AvailableQuickStepUpgrade) + "\n";

                has_text = true;
                count++;
            }
           
            if (String.IsNullOrEmpty(upgrader.AvailableIdentModuleUpgrade) == false)
            {
                if (has_text)
                    arg.DialogArgs.Message += "\n";

                arg.DialogArgs.Message += String.Format(Catalog.GetString(@"	- IdentModule {0}
	  (reference database / update certificate)"),
                                                        upgrader.AvailableIdentModuleUpgrade) + "\n";
                has_text = true;
                count++;
            }

            if (String.IsNullOrEmpty(upgrader.AvailableQuantifierModuleUpgrade) == false)
            {
                if (has_text)
                    arg.DialogArgs.Message += "\n";

                arg.DialogArgs.Message += String.Format(Catalog.GetString(@"	- QuantifierModule {0}
	  (reference database / update certificate)"),
                                                        upgrader.AvailableQuantifierModuleUpgrade) + "\n";

                has_text = true;
                count++;
            }

            if (count > 1)
                arg.DialogArgs.Message += "\n\n" + Catalog.GetString("Do you want to install them now?");
            else
                arg.DialogArgs.Message += "\n\n" + Catalog.GetString("Do you want to install it now?");


            arg.DialogArgs.Title = Catalog.GetString("Upgrade Information");
            this.UpdateGuiNeeded?.Invoke(arg);

            if (arg.DialogArgs.Response == DialogRespnseType.Yes)
            {
                if (is_automatic == false)
                {
                    if (this.ProtocolManager.CheckProtocolSaveState(this) == false)
                        return;
                }

                upgrader.InstallUpgrades();

                if (is_automatic)
                {
                    ApoActionArg action_arg = new ApoActionArg();
                    action_arg.Action = ApoActionType.CloseHost;
                    this.ActionNeeded?.Invoke(action_arg);
                }
                else
                {
                    this.Exit(true);
                }
            }
        }

        private void ShowNoUpgradeMessageDialog(bool is_automatic)
        {
            if (is_automatic == true)
                return;

            UpdateArgs arg = new UpdateArgs();
            arg.DialogArgs.StandardDialogType = StandardDialogType.Info;
            arg.DialogArgs.Message = Catalog.GetString("There are no upgrades available.");
            this.UpdateGuiNeeded?.Invoke(arg);
        }
    }
}
