// 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.AnalysisModule;
using Hiperscan.ApoIdentCore.ActionControl;
using Hiperscan.ApoIdentCore.GuiControl;
using Hiperscan.GuiExtensions;

namespace Hiperscan.ApoIdentCore
{
    public partial class AppControl
    {
        private void Exit(bool silent = false)
        {
            if (this.GlobalStates.ProgramExitCalled == true)
                return;

            this.GlobalStates.SilentExit = silent;
            this.GlobalStates.ExitContiueAction = true;

            bool continue_action = this.ProtocolManager.CheckProtocolSaveState(this);

            if (continue_action == false && this.GlobalStates.SilentExit == false)
                return;

            ApoActionArg arg = new ApoActionArg();
            arg.Action = ApoActionType.BeginExit;
            this.ActionNeeded?.Invoke(arg);

            if (this.GlobalStates.ExitContiueAction == false)
                return;

            this.GlobalStates.ProgramExitCalled = true;
            this.RequestQuit();

            this.GlobalStates.Busy = true;
            UpdateArgs update_arg = new UpdateArgs();
            update_arg.AnimationType = Enums.ProgramState.Working;
            update_arg.CursorState = CursorState.Busy;
            this.UpdateGuiNeeded?.Invoke(update_arg);

            arg = new ApoActionArg();
            arg.Action = ApoActionType.ContinueExit;
            this.ActionNeeded?.Invoke(arg);

            this.Disconnect();
            this.SaveConfig();

            try
            {
                this.SubstanceManager.StopServers();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to terminate server: " + ex.Message);
            }

            arg = new ApoActionArg();
            arg.Action = ApoActionType.EndExit;
            this.ActionNeeded?.Invoke(arg);
        }
    }
}
