// 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.Enums;
using Hiperscan.ApoIdentCore.GuiControl;
using Hiperscan.ApoIdentCore.SectionManager.Result;
using Hiperscan.GuiExtensions.Dialog;
using Hiperscan.Unix;

namespace Hiperscan.ApoIdentCore
{
    public partial class AppControl
    {
        public void InitResultManager()
        {
            if (this.ResultManager == null)
            {
                this.ResultManager = new ResultManager(this.Locale,
                                                       this.ProfileManager,
                                                       this.GlobalStates);

                this.ResultManager.MisIdentificationDetected += this.OnMisIdentificationDetected;
                this.ResultManager.SetValidStateChangedEvents(this.OnResultFieldValidStateChanged);
                this.ResultManager.SetValueChangedEvents(this.OnProtocolValueChanged);
                this.ResultManager.AdditopalTestField.ValueChanged += this.OnAdditionalTestValueChanged;
                this.ResultManager.CompleteStateChanged += this.OnResultCompleteStateChanged;
            }
        }

        public void SetComment(string text)
        {
            if (this.GuiSyncControl.IsResultSectionUpdating)
                return;

            this.ResultManager.Comment.Entry = text;
        }

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

            UpdateArgs arg = new UpdateArgs();
            arg.Result = UpdateCategory.Reset;
            arg.DialogArgs.ApoDialogType = ApoDialogType.AdditionalTest;
            this.UpdateGuiNeeded?.Invoke(arg);

            this.ResultManager.AdditopalTestField.Entry = this.ResultManager.CurrentAdditionalTest.ProtocolText;
            this.ResultManager.CustomerEvaluationField.Entry = this.ResultManager.CurrentAdditionalTest.ProtocolCustomerEvaluation;

            this.ProgramSync.LeaveCriticalZone();
        }

        public void ShowNirResultPlot()
        {
            try
            {
                this.ProgramSync.EnterCriticialZone();

                UpdateArgs arg = new UpdateArgs();

                if (this.ResultManager.IsNirMeasurable == false)
                {
                    arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                    arg.DialogArgs.Message = Catalog.GetString("For NIR-inactive substances spectrum details are not available.");
                }
                else
                {
                    arg.DialogArgs.ApoDialogType = ApoDialogType.ResultPlot;
                }

                this.UpdateGuiNeeded?.Invoke(arg);
            }
            catch (Exception ex)
            {
                UpdateArgs arg = new UpdateArgs();
                arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                arg.DialogArgs.Message = String.Format(Catalog.GetString("Error while calculating the spectra: {0}"),
                                          ex.Message);
                arg.DialogArgs.Exception = ex;
                this.UpdateGuiNeeded?.Invoke(arg);
            }
            finally
            {
                this.ProgramSync.LeaveCriticalZone();
            }
        }

        public void ShowResultRatingList()
        {
            try
            {
                this.ProgramSync.EnterCriticialZone();

                UpdateArgs arg = new UpdateArgs();

                if (this.ResultManager.IsNirMeasurable == false)
                {
                    arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                    arg.DialogArgs.Message = Catalog.GetString("For NIR-inactive substances spectrum details are not available.");
                }
                else
                {
                    arg.DialogArgs.ApoDialogType = ApoDialogType.ResultList;
                }

                this.UpdateGuiNeeded?.Invoke(arg);
            }
            catch (Exception ex)
            {
                UpdateArgs arg = new UpdateArgs();
                arg.DialogArgs.StandardDialogType = StandardDialogType.ErrorWithServiceMessage;
                arg.DialogArgs.Message = String.Format(Catalog.GetString("Cannot show result list: {0}"),
                                          ex.Message);
                arg.DialogArgs.Exception = ex;
                this.UpdateGuiNeeded?.Invoke(arg);
            }
            finally
            {
                this.ProgramSync.LeaveCriticalZone();
            }
        }

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

        private void OnAdditionalTestValueChanged(object sender, EventArgs e)
        {
            UpdateArgs args = new UpdateArgs();
            args.Result = UpdateCategory.Reset;
            this.UpdateGuiNeeded?.Invoke(args);
        }

        private void OnMisIdentificationDetected(UpdateArgs arg)
        {
            ApoActionArg action_arg = new ApoActionArg();
            action_arg.Action = ApoActionType.CloseWindows;
            this.ActionNeeded?.Invoke(action_arg);

            this.UpdateGuiNeeded?.Invoke(arg);

            if (arg.DialogArgs.Response == DialogRespnseType.Yes)
            {
                if (arg.AnimationType == ProgramState.IdentificationFluidFailed)
                    this.DocumentManager.ShowPDF("misidentification_liquids.pdf");
                else
                    this.DocumentManager.ShowPDF("misidentification_solids.pdf");
            }
        }

        private void OnResultCompleteStateChanged(object sender, EventArgs e)
        {
            this.ProtocolManager.AreResultDataComplete = this.ResultManager.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 ResultManager ResultManager { get; set; }
    }
}
