// 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 System.IO;
using System.Reflection;
using Hiperscan.AnalysisModule;
using Hiperscan.ApoIdentCore.ComplexFinder;
using Hiperscan.ApoIdentCore.Enums;
using Hiperscan.ApoIdentCore.SectionManager.Measuring.Simulator;
using Hiperscan.ApoIdentCommon.ApoConfig.Cache;
using Hiperscan.SGS;
using Hiperscan.Spectroscopy;
using Hiperscan.Spectroscopy.IO;
using Hiperscan.Spectroscopy.Method;
using Hiperscan.Unix;

namespace Hiperscan.ApoIdentCore.SectionManager.Measuring
{
    public partial class MeasuringManager
    {
        public event MeasuringArg.MeasuringProgressedHandler MeasuringProgressed = null;


        private void OnMeasurementStarted(object sender, EventArgs e)
        {
            if (this.Finder.DeviceExists == false)
                return;

            if (this.IsNirMeasurable == false)
                return;

            MeasuringArg arg = new MeasuringArg();
            arg.MeasuringAction = this.GetMeasuringState();
            arg.IsExecuting = true;

            switch (arg.MeasuringAction)
            {
                case ProgramState.MeasuringBlackReference:
                case ProgramState.MeasuringWhiteReference:
                case ProgramState.MeasuringWhiteInsertReference:
                    this.MeasuringProgressed?.Invoke(arg);
                    this.ReferenceControl.StopWaitingForReference();
                    break;

                default:
                    this.MeasuringProgressed?.Invoke(arg);
                    break;
            }
        }

        private void OnWaitForExternalBlackReference()
        {
            this.ReferenceControl.SetState(ProgramState.MeasuringBlackReference);
            MeasuringArg arg = new MeasuringArg();
            arg.IsExecuting = false;
            arg.MeasuringAction = ProgramState.MeasuringBlackReference;
            this.MeasuringProgressed?.Invoke(arg);
            this.Finder.FinderButton.LeaveMeasureCycle();
            this.ReferenceControl.WaitForReference();
            this.ReferenceControl.CheckForAbortReferencing();
        }

        private void OnWaitForExternalWhiteReference()
        {
            ProgramState reference_type = this.Finder.IsInsertActive ? ProgramState.MeasuringWhiteInsertReference : ProgramState.MeasuringWhiteReference;
            this.ReferenceControl.SetState(reference_type);
            MeasuringArg arg = new MeasuringArg();
            arg.IsExecuting = false;
            arg.MeasuringAction = reference_type;
            this.MeasuringProgressed?.Invoke(arg);
            this.Finder.FinderButton.LeaveMeasureCycle();
            this.ReferenceControl.WaitForReference();
            this.ReferenceControl.CheckForAbortReferencing();
        }

        private void OnExternalCalibrationFinished(bool success)
        {
            this.ReferenceControl.Reset();
        }

        private void OnFinderInternalCalibrationStarted()
        {
            MeasuringArg arg = new MeasuringArg();
            arg.IsExecuting = true;
            arg.MeasuringAction = ProgramState.MeasuringInternalRecalibration;
            this.MeasuringProgressed?.Invoke(arg);
        }


        private void OnFinderInternalCalibrationFinished()
        {
            if (this.Finder.FinderExists == false)
                return;

            if (this.SubstanceCatalog.IsSubstanceSelected == false)
                return;

            if (this.SubstanceCatalog.ModelClass.SubstanceType != SubstanceType.Fluid)
                return;
        }

        public void AcquireSpectrum(bool simulate, bool fluid)
        {
            this.ContinueAction = true;
            this.BeforeMeasuringStarted?.Invoke(this, EventArgs.Empty);
            if (this.ContinueAction == false)
                return;

            if (simulate == false)
            {
                ushort average = this.Finder.Device.CurrentConfig.Average;

                this.Finder.Device.CurrentConfig.Average = this.Finder.GetAverage();
                this.Finder.Device.WriteConfig();

                this.Finder.Current.Acquire(fluid);
                this.Finder.Current.SaveReferenceSpectrum(this.Finder.Current.CurrentSampleSpectrum,
                                                          fluid ? SpectrumType.FluidSpecimen : SpectrumType.SolidSpecimen,
                                                          false, string.Empty);


                this.ProcessedSpectrum = this.Finder.Current.Process(fluid);
                this.ProcessedSpectrum.WlcMasterSpectrumId = (byte)this.Finder.Current.ReferenceWheelVersion;

                if (this.Finder.ProductId != ProductId.APOIDENT_2X_ES20)
                    this.ProcessedSpectrum.LimitBandwidth = true;

                this.Finder.Device.CurrentConfig.Average = average;
                this.Finder.Device.WriteConfig();
            }
            else
            {
                this.processed_spectrum = SpectrumSimulator.LoadSpectrum();
            }
        }

        public void AcquireTransflectance()
        {
            bool was_referencing_pending = this.Finder.Current.ReferencingIsPending;
            this.Finder.Current.AcquireExternalTransflectanceReference();
            if (was_referencing_pending && this.Finder.Current.RecalibrationIsPending)
            {
                throw new Exception(Catalog.GetString("Referencing must be finished a short time period (max. 35 Minutes) after acquisition of the first spectrum. This condition was not fulfilled. Please repeat measurement."));
            }
        }

        public void SaveErrorSampleSpectrum()
        {
            try
            {
                this.Finder.Current.SaveReferenceSpectrum(this.Finder.Current.CurrentSampleSpectrum,
                                                          this.SubstanceCatalog.ModelClass.SubstanceType == SubstanceType.Fluid ? SpectrumType.FluidSpecimen : SpectrumType.SolidSpecimen,
                                                          true, string.Empty);
            }
#pragma warning disable RECS0022 // catch-Klausel, die System.Exception abfängt und keinen Text aufweist
            catch { }
#pragma warning restore RECS0022 // catch-Klausel, die System.Exception abfängt und keinen Text aufweist
        }

        public ProgramState GetMeasuringState()
        {
            if (this.SubstanceCatalog == null)
                return ProgramState.None;

            if (this.SubstanceCatalog.IsSubstanceSelected == false)
                return ProgramState.None;

            if (this.IsNirMeasurable == false)
                return ProgramState.NotMeasurable;

            if (this.Finder.FinderExists == false)
                return ProgramState.None;

            if (this.ReferenceControl.ReferencingType != ProgramState.None)
                return this.ReferenceControl.ReferencingType;

            if (this.SubstanceCatalog.ModelClass.SubstanceType == SubstanceType.Fluid)
            {
                if (this.Finder.IsStandardFinderRecalibrationPending)
                {
                    if (this.Finder.IsFinderSD)
                        return ProgramState.MeasuringTransflectanceAu;
                    else
                        return ProgramState.MeasuringTransflectance;
                }
                else
                {
                    return ProgramState.MeasuringFluid;
                }
            }
            else
            {
                if (this.SubstanceCatalog.ModelClass.SubstanceType == SubstanceType.SampleInsertOnly || this.Finder.IsInsertActive)
                {
                    return ProgramState.MeasuringInsert;
                }
                else
                {
                    if (this.SubstanceCatalog.AnalysisType == AnalysisType.Identification)
                        return ProgramState.MeasuringSolid;

                    return ProgramState.MeasuringCannabis;
                }
            }
        }

        public bool CanMeasureInsert()
        {
            if (this.SubstanceCatalog == null)
                return false;

            if (this.IsReferencing)
                return false;

            if (this.IsNirMeasurable == false)
                return false;

            if (this.SubstanceCatalog.AnalysisType == AnalysisType.Quantification)
                return false;

            bool is_es_20 = this.Finder.IsApoIdent_2_1 &&
                                    this.SubstanceCatalog.ModelClass.SubstanceType == SubstanceType.Solid;

            bool is_can_insert = this.SubstanceCatalog.Substance.CanInsert;

            return (is_es_20 || is_can_insert) && this.SubstanceCatalog.ModelClass.SubstanceType != SubstanceType.SampleInsertOnly;
        }

        public void ActivateRecalibrationTimer()
        {
            this.HasFirstTransflectance = true;
            this.RecalibrationTimer.RecalibrationTimeoutMilliSeconds = this.Finder.RecalibrationTimmeoutMilliSeconds;
            this.RecalibrationTimer.RecalibrationTimeStamp = this.Finder.RecalibrationTimeStamp;
            this.RecalibrationTimer.StartPolling();
        }

        public void DeactivateRecalibrationTimer()
        {
            this.RecalibrationTimer.StopPolling();
            this.HasFirstTransflectance = false;
        }

        public bool IsRecalibrtionTimerActive
        {
            get
            {
                return this.HasFirstTransflectance && this.IsReferencing == false;
            }
        }

        public ReferencingControl ReferenceControl { get; private set; }
        private  RecalibrationTimer RecalibrationTimer { get; set; } = new RecalibrationTimer();
        private bool HasFirstTransflectance { get; set; }
        public bool ContinueAction { get; set; } = true;
    }
}