// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2021 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 static Hiperscan.Extensions.ApoIdent.Configurations;

namespace Hiperscan.Extensions.ApoIdent
{
    public partial class ApoIdentApplication
    {
        private void InitConfig()
        {
            this.Config = new Configurations(this.Control.Host.ConfigurationDirPath);

            FilesAndDirs.Init(this.Config,
                              this.Control.Host.ProfileChangedMode,
                              this.Control.Host.ConfigurationDirPath);

            foreach (Configurations.ProfilePreferences profile in this.Config.Profiles.AllProfiles.Values)
                this.CheckMissingArchive(profile);

            LocalizedSubstanceExtensions.Init(this.Config.IdentModuleSettings.Locale);

            this.Config.ConnectionSettingsChanged += this.OnConnectionSettingsChanged;
            this.Config.ProfileChanged += this.OnProfileChanged;
            this.Config.ProfileSettingsChanged += this.OnProfileSettingsChanged;
            AdditionalTestWindow.WindowClosed += this.OnResultAdditionalTestsWindowClosed;
        }

        private void CheckSettings()
        {
            if (this.Config.Profiles.NeedCheck == true || this.Config.Profiles.Current == null)
            {
                this.Update(ApoIdentApplicationState.CheckSettings);
            }
        }

        private void OnConnectionSettingsChanged(object sender, EventArgs e)
        {
            lock (this.Control.DeviceEventsSync)
            {
                if (this.Control.ConnectionSuccess && this.Finder.Device.Info.IsRemote == false)
                    return;

                if (this.Control.QuitRequested == true)
                    return;

                if (this.Control.IsDisconnecting)
                    return;

                if (this.Control.ConnectionIsInitializing)
                    return;
            }

            System.Threading.Tasks.Task.Run(() => this.InitConnection());
        }

        private void OnProfileChanged(object sender, EventArgs e)
        {
            this.CheckArchive();
            this.SubstanceManagement.InitModelExtension();

            this.SubstanceManagement.ResetSelection();
            this.Control.Busy = false;
            this.Update(ApoIdentApplicationState.ConfigProfileChanged);
        }

        private void OnProfileSettingsChanged(object sender, EventArgs e)
        {
            ProfilePreferences profile = sender as Configurations.ProfilePreferences;
            if (profile.ArchiveChanged)
                this.CreateArchive(profile);

            this.CheckMissingArchive(profile);
            this.Update(ApoIdentApplicationState.ConfigProfileSettingsChanged);
        }

        private void OnConfigComboChanged(object sender, EventArgs e)
        {
            if (this.Control.IsGuiUpdating == true)
                return;

            lock (this.Control.Transaction)
            {
                if (this.CheckForNotSavedProtocolDetails() == false)
                {
                    this.test_profile_combobox.Active = this.Config.Profiles.CurrentIndex(this.Config.Profiles.Current);
                    return;
                }

                this.SubstanceManagement.ResetSelection();
                this.Control.Busy = true;
                this.Update(ApoIdentApplicationState.ConfigBeginProfileChanged);

                string new_profile = this.test_profile_combobox.ActiveText;

                System.Threading.Tasks.Task.Run(() =>
                {
                    lock (this.Control.Transaction)
                    {
                        Config.StashAll();
                        Config.Profiles.NewProfileName = new_profile;
                        Config.UnstashAll();
                        this.Finder?.UpdateReferencingDir(this.Config.Profiles.Current.ArchiveMissing);
                    }
                });
            }
        }

        private void OnTestUserEntryChanged(object sender, EventArgs e)
        {
            if (Control.IsGuiUpdating)
                return;

            this.Control.ProtocolState.UpdateUserField(this.TestUserEntry.IsValid);
            this.Control.ProtocolState.SetFlag(ProtocolStates.ProtocolNotSaved);
            this.Update(ApoIdentApplicationState.ProtocolDataChanged);
        }

        public Configurations Config { get; private set; } = null;
    }
}
