// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2018 Thomas Klose & Torsten Schache, 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.Enums;
using Hiperscan.ApoIdentCore.GuiControl;
using Hiperscan.ApoIdentCore.SectionManager.Pharmacy;
using Hiperscan.ApoIdentCommon.ApoConfig;
using Hiperscan.GuiExtensions;
using Hiperscan.GuiExtensions.Dialog;

namespace Hiperscan.ApoIdentCore
{
    public partial class AppControl
    {
        private void InitPharmacyManager()
        {
            if (this.PharmacyManager == null)
            {
                this.PharmacyManager = new PharmacyManager(this.Config.Profiles);
                this.PharmacyManager.ArchiveMissed += this.OnArchiveMissed;
                this.PharmacyManager.ProfileSettingsCheckNeeded += this.OnProfileSettingsCheckNeeded;

                this.PharmacyManager.Operator.ValueChanged += this.OnProtocolValueChanged;
                this.PharmacyManager.Operator.ValidStateChanged += this.OnOperatorValidStateChanged;
                this.PharmacyManager.CompleteStateChanged += this.OnPharmacyCompleteStateChanged;
            }
        }

        public void SetOperatorName(string name)
        {
            if (this.GuiSyncControl.IsPharmacySectionUpdating)
                return;

            this.PharmacyManager.Operator.Entry = name;
        }

        public void ChangeProfile(string profile_name)
        {
            if (this.GuiSyncControl.IsPharmacySectionUpdating == true)
                return;

            profile_name = (profile_name ?? String.Empty).Trim();

            if (String.IsNullOrEmpty(profile_name) == true)
                return;

            this.ProgramSync.EnterCriticialZone();

            if (this.ProtocolManager.CheckProtocolSaveState(this) == true)
            {
                this.ResetSubstanceSelection();
                this.GlobalStates.Busy = true;

                UpdateArgs args = new UpdateArgs();
                args.CursorState = CursorState.Busy;
                this.UpdateGuiNeeded?.Invoke(args);

                System.Threading.Tasks.Task.Run(() =>
                {
                    this.ProgramSync.EnterCriticialZone();

                    this.Config.StashAll();
                    this.ProfileManager.NewProfileName = profile_name;
                    this.Config.UnstashAll();

                    this.MeasuringManager.Finder.UpdateReferencingDir(this.ProfileManager.CurrentProfile);
                    this.MeasuringManager.Finder.ResetAllReferences();

                    this.GlobalStates.Busy = false;
                    UpdateArgs arg = UpdateArgs.GetResetArg();
                    arg.CursorState = CursorState.Normal;
                    this.UpdateGuiNeeded?.Invoke(arg);

                    this.PharmacyManager.CheckArchive();
                    this.SetReadyForSubstanceInput();

                    this.ProgramSync.LeaveCriticalZone();
                });
            }

            this.ProgramSync.LeaveCriticalZone();
        }

        private void OnArchiveMissed(object sender, EventArgs e)
        {
            UpdateArgs args = new UpdateArgs();
            args.CursorState = CursorState.Normal;
            args.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
            args.DialogArgs.Message = (sender as PharmacyManager).ArchiveMissingMessage;
            args.DialogArgs.UseMarkup = true;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnProfileSettingsCheckNeeded(object sender, EventArgs e)
        {
            UpdateArgs args = new UpdateArgs();
            args.DialogArgs.ApoDialogType = ApoDialogType.Preferences;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnOperatorValidStateChanged(object sender, EventArgs e)
        {
            UpdateArgs args = new UpdateArgs();
            args.Pharmacy = UpdateCategory.ValidStates;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnProfilesChanged(object sender, EventArgs e)
        {
            this.SpecimenManager.SetCurrency();

            this.PharmacyManager.CheckArchive();

            this.InitNotMeasurableSubstances();
            this.ResetSubstanceSelection();

            this.GlobalStates.Busy = false;
            UpdateArgs args = UpdateArgs.GetResetArg();
            args.Pharmacy = UpdateCategory.All;
            args.Substance = UpdateCategory.All;
            this.UpdateGuiNeeded?.Invoke(args);

            this.SetReadyForSubstanceInput();
        }

        private void OnProfileSettingsChanged(object sender, EventArgs e)
        {
            this.SpecimenManager.SetCurrency();

            ProfileSettings profile = sender as ProfileSettings;
            if (profile.ArchiveChanged)
            {
                this.PharmacyManager.CreateArchive(profile);

                if (profile.Name == this.ProfileManager.CurrentProfile?.Name)
                    this.MeasuringManager.Finder.ResetAllReferences();
            }

            profile.CheckMissingArchive();

            UpdateArgs args = UpdateArgs.GetResetArg();
            args.Substance = UpdateCategory.All;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnPharmacyCompleteStateChanged(object sender, EventArgs e)
        {
            this.ProtocolManager.ArePharmacyDataComplete = this.PharmacyManager.IsComplete;

            UpdateArgs args = new UpdateArgs();
            args.Protocol = UpdateCategory.Sensitives;
            if (this.ResultManager.AnalysisResultExists)
            {
                if (this.ProtocolManager.IsComplete)
                    args.AnimationType = ProgramState.ReadyForProtocolCreation;
                else
                    args.AnimationType = ProgramState.ReadyForProtocolInput;
            }
            this.UpdateGuiNeeded?.Invoke(args);
        }

        public PharmacyManager PharmacyManager { get; private set; }
    }
}
