// 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.Unix;
using Hiperscan.ApoIdentCore.SectionManager.Protocol;
using Hiperscan.ApoIdentCore.GuiControl;
using Hiperscan.ApoIdentCore.Enums;
using Hiperscan.ApoIdentCommon.ApoConfig;
using Hiperscan.GuiExtensions.Dialog;
using Hiperscan.ApoIdentCore.SectionManager.Substance.SubstanceSelection;
using System.Linq;

namespace Hiperscan.ApoIdentCore
{
    public partial class AppControl
    {
        private void InitProtocolManager()
        {
            this.ProtocolManager = new ProtocolManager(this.ProfileManager, 
                                                       this.LabelPrinterSettings);

            this.ProtocolManager.DemoVersionDetected += this.OnDemoProfileDetected;
            this.ProtocolManager.SaveResponseNeeded += (arg) => this.UpdateGuiNeeded(arg);
            this.ProtocolManager.DataExchangeSaved += this.OnDataExportSaved;
            this.ProtocolManager.ProtocolSaved += this.OnProtocolSaved;
            this.ProtocolManager.DataExchangeSuccessStateChanged += this.OnDataExchangeSuccessStateChanged;
        }

        public void SaveProtocol()
        {
            this.ProgramSync.EnterCriticialZone();
            this.ProtocolManager.SaveProtocol(this);
            this.ProgramSync.LeaveCriticalZone();
        }

        public void ShowProtocol()
        {
            this.ProgramSync.EnterCriticialZone();

            if (this.ProtocolManager.SaveProtocol(this) == true)
            {
                if (this.ProtocolManager.ShowProtocol() == false)
                {
                    UpdateArgs arg = new UpdateArgs();
                    arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                    arg.DialogArgs.Exception = this.ProtocolManager.Exception;
                    arg.DialogArgs.Message = this.ProtocolManager.ErrorMessage;
                    arg.DialogArgs.Title = this.ProtocolManager.ErrorTitle;
                    this.UpdateGuiNeeded?.Invoke(arg);
                }
            }

            this.ProgramSync.LeaveCriticalZone();
        }

        public void PrintProtocol()
        {
            this.ProgramSync.EnterCriticialZone();

            if (this.ProtocolManager.SaveProtocol(this) == true)
            {
                if (this.ProtocolManager.PrintProtocol() == false)
                {
                    UpdateArgs arg = new UpdateArgs();
                    arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                    arg.DialogArgs.Exception = this.ProtocolManager.Exception;
                    arg.DialogArgs.Message = this.ProtocolManager.ErrorMessage;
                    arg.DialogArgs.Title = this.ProtocolManager.ErrorTitle;
                    this.UpdateGuiNeeded?.Invoke(arg);
                }
            }

            this.ProgramSync.LeaveCriticalZone();
        }

        public void LabelPrintProtocol()
        {
            this.ProgramSync.EnterCriticialZone();

            if (this.ProtocolManager.SaveProtocol(this) == true)
            {
                if (this.ProtocolManager.LabelPrint() == false)
                {
                    UpdateArgs arg = new UpdateArgs();
                    arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                    arg.DialogArgs.Exception = this.ProtocolManager.Exception;
                    arg.DialogArgs.Message = this.ProtocolManager.ErrorMessage;
                    arg.DialogArgs.Title = this.ProtocolManager.ErrorTitle;
                    this.UpdateGuiNeeded?.Invoke(arg);
                }
            }

            this.ProgramSync.LeaveCriticalZone();
        }


        private void OnDemoProfileDetected(object sender, EventArgs e)
        {
            UpdateArgs args = new UpdateArgs();
            args.DialogArgs.StandardDialogType = StandardDialogType.Info;
            args.DialogArgs.Message = ProfileManager.DEMO_VERSION_NOTE;
            args.DialogArgs.Title = Catalog.GetString("Invalid Address Data");
            args.DialogArgs.UseMarkup = true;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnProtocolSaved(object sender, EventArgs e)
        {
            UpdateArgs arg = new UpdateArgs();

            if (this.ProtocolManager.SaveSuccess)
            {
                arg.AnimationType = ProgramState.Saved;
                arg.Protocol = UpdateCategory.Sensitives;
                arg.Pharmacy = UpdateCategory.SetValues;
                arg.Specimen = UpdateCategory.SetValues;
                this.UpdateGuiSettings();
            }
            else
            {
                arg.AnimationType = ProgramState.SavingFailed;
                arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                arg.DialogArgs.Exception = this.ProtocolManager.Exception;
                arg.DialogArgs.Message = this.ProtocolManager.ErrorMessage;
                arg.DialogArgs.Title = this.ProtocolManager.ErrorTitle;
            }

            this.UpdateGuiNeeded?.Invoke(arg);
        }

        private void UpdateGuiSettings()
        {
            if (this.SubstanceManager.SubstancesCatalog.SelectionType == SubstanceSelectionType.ThirdParty)
                return;

            string user_name = this.PharmacyManager.Operator.GetEntryValue().Trim();
            if (this.GuiSettings.UserCompletion.Contains(user_name) == false)
                this.GuiSettings.UserCompletion.Add(user_name);

            string producer = this.SpecimenManager.Producer.GetEntryValue().ToLower().Trim();
            if (this.GuiSettings.ProducerCompletion.Any(p => p.ToLower() == producer) == false)
                this.GuiSettings.ProducerCompletion.Add(this.SpecimenManager.Producer.GetEntryValue().Trim());
            
        }

        private void OnDataExportSaved(object sender, EventArgs e)
        {
            UpdateArgs arg = new UpdateArgs();

            if (this.ProtocolManager.DataExchangeSuccess)
            {

                arg.DialogArgs.StandardDialogType = StandardDialogType.Info;
                arg.DialogArgs.Message = this.ProtocolManager.DataExchangeMessage;
                arg.Substance = UpdateCategory.Reset;
                arg.Specimen = UpdateCategory.Sensitives;
                arg.Measuring = UpdateCategory.Sensitives;
            }
            else
            {
                arg.AnimationType = ProgramState.SavingFailed;
                arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                arg.DialogArgs.Exception = this.ProtocolManager.Exception;
                arg.DialogArgs.Message = this.ProtocolManager.ErrorMessage;
                arg.DialogArgs.Title = this.ProtocolManager.ErrorTitle;
            }

            this.UpdateGuiNeeded?.Invoke(arg);
        }

        private void OnProtocolValueChanged(object sender, EventArgs e)
        {
            this.ProtocolManager.IsProtocolSaved = false;

            UpdateArgs args = new UpdateArgs();
            args.Protocol = UpdateCategory.Sensitives;

            if (this.ResultManager.AnalysisResultExists)
            {
                if (this.ProtocolManager.IsComplete == false)
                    args.AnimationType = ProgramState.ReadyForProtocolInput;
                else
                    args.AnimationType = ProgramState.ReadyForProtocolCreation;
            }

            this.UpdateGuiNeeded?.Invoke(args);
        }

        public ProtocolManager ProtocolManager { get; private set; }
    }
}
