// 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 System.Drawing;
using Gtk;
using Hiperscan.NPlotEngine;
using Hiperscan.Spectroscopy;
using Hiperscan.Spectroscopy.Method;
using Hiperscan.Unix;

namespace Hiperscan.Extensions.ApoIdent
{
    public partial class ApoIdentApplication
    {
        private const string SUGGESTION_INFO = @"
Hinweis: Diese Prüfvorschriften wurden vom Institut für Pharmazie der Universität Leipzig und der Apothekerin Elke Parchmann erstellt und verifiziert. Ziel ist es, eine eindeutige Unterscheidung innerhalb einer Gruppe/Klassifizierung zu gewährleisten. Um dies sicherzustellen, müssen für die betreffende Substanz alle ergänzenden Prüfungen durchgeführt werden. Bei den angegebenen Prüfungen handelt es sich um Abwandlungen und ggf. Ergänzungen bereits etablierter Prüfvorschriften einschlägiger Monographiesammlungen (Ph. Eur., DAC/NRF, apothekengerechte Prüfvorschriften).

<i>Es obliegt dem zuständigen Apotheker zu entscheiden, ob der Vorschlag für diese Substanz angewendet werden sollen. Er muss diese Entscheidung dokumentieren und ggf. auch gegenüber der Aufsichtsbehörde verteidigen, falls diese die Validität der Kombination aus NIR-Prüfung und ergänzender Prüfung anzweifelt.</i>
        ";

        private void CheckIdentificationResult()
        {
            if (this.IdentServerClient.IsTruePositive)
            {
                this.Control.NoMisIdentificationYet = true;
                return;
            }

            string message = Catalog.GetString("The identification failed. One reason can be a faulty operation.");

            if (this.Control.NoMisIdentificationYet == false)
            {
                this.Update(ApoIdentApplicationState.MeasuringResultCheckRepeated, message);
                return;
            }

            this.Control.NoMisIdentificationYet = false;
            this.Update(ApoIdentApplicationState.MeasuringResultCheck, message);
            if (this.DialogResponse == ResponseType.Yes)
            {
                if (this.SubstanceManagement.CurrentModelClass.SubstanceType == SubstanceType.Fluid)
                    this.ShowPDF("misidentification_liquids.pdf");
                else
                    this.ShowPDF("misidentification_solids.pdf");
            }
        }

        private void OnResultSuggestionButtonClicked(object sender, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                try
                {
                    string link = this.SubstanceManagement.CurrentSubstance.PdfLinkAdditionalTest;
                    this.Update(ApoIdentApplicationState.ResultPreSuggestion, ApoIdentApplication.SUGGESTION_INFO);

                    string pdf_file = FilesAndDirs.AdditionalDocuFile;
                    Hiperscan.PdfLib.Pdf.Open(pdf_file, link);
                }
                catch (Exception ex)
                {
                    string message = String.Format(Catalog.GetString("Cannot open additional tests document: {0}"),
                                                   ex.Message);

                    this.Update(ApoIdentApplicationState.ShowErrorDialogWithoutSerivceDialog, message, ex);
                }
            }
        }

        private void OnResultAdditionalTestsClicked(object sender, EventArgs e)
        {
            lock(this.Control.Transaction)
            {
                this.Update(ApoIdentApplicationState.ResultAdditionalTestsWindowStart);
            }
        }

        private void OnResultAdditionalTestsWindowClosed(object sender, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                bool changes = (bool)sender;

                if (changes)
                {
                    this.Control.ProtocolState.SetFlag(ProtocolStates.ProtocolNotSaved);
                    this.CheckAdditionalTestAsMandatory();
                    this.Update(ApoIdentApplicationState.ResultAdditionalTestsWindowClosed);
                }
            }
        }

        private void OnResultCommentEntryChanged(object sender, EventArgs e)
        {
            if (this.Control.IsGuiUpdating)
                return;
            lock (this.Control.Transaction)
            {
                this.Control.ProtocolState.SetFlag(ProtocolStates.ProtocolNotSaved);
                this.Update(ApoIdentApplicationState.ProtocolDataChanged);
            }
        }

        private void OnResultNirButtonClicked(object sender, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                this.Update(ApoIdentApplicationState.ResultShowPlots);
            }
        }

        private void ShowResultPlots()
        {
            if (this.Control.CreateNotMeasurableReport == true)
            {
                string message = String.Format(Catalog.GetString("Spectrum details are not available when a NIR inactive substance ist selected."));
                this.Update(ApoIdentApplicationState.ShowErrorDialogWithoutSerivceDialog, message);
                return;
            }

            Hiperscan.Spectroscopy.DataSet original = null;
            Hiperscan.Spectroscopy.DataSet backproj = null;
            Hiperscan.Spectroscopy.DataSet matchbp = null;
            Hiperscan.Spectroscopy.DataSet difference = null;

            try
            {
                original = this.Control.CurrentProcessedSpectrum.Absorbance;
                backproj = this.IdentServerClient.Result.SpectrumBackProjection;

                if (this.IdentServerClient.IsTruePositive)
                {
                    matchbp = this.IdentServerClient.Result.MatchBackProjection;
                    difference = backproj - matchbp;
                }

                original.Label = Catalog.GetString("Acquired spectrum");
                original.Color = Color.Blue;
                backproj.Label = Catalog.GetString("Back projection of acquired spectrum");
                backproj.Color = Color.Blue;
                backproj.Id = "0_backprojection";

                if (this.IdentServerClient.IsTruePositive == true)
                {
                    matchbp.Label = Catalog.GetString("Back projection of reference spectrum");
                    matchbp.Color = Color.Red;
                    matchbp.Id = "1_match";
                    difference.Label = Catalog.GetString("Difference of back projections*");
                    difference.Color = Color.Green;
                    difference.LineStyle = LineStyle.Dash;
                    difference.Id = "2_difference";
                }

                Dialog dialog = new Dialog(Catalog.GetString("Absorbance Spectra"), this.MainWindow, DialogFlags.Modal)
                {
                    IconList = ApoIdentStock.FinderIcons
                };

                dialog.AddButton(Stock.Close, ResponseType.Close);
                dialog.WindowPosition = WindowPosition.CenterAlways;
                dialog.HasSeparator = true;
                dialog.WidthRequest = (int)(780 * 1.4);
                dialog.HeightRequest = (int)(400 * 1.4);

                IPlotEngine plot1 = new NPlotEngine.NPlotEngine(PlotEngineType.Synchronous);
                IPlotEngine plot2 = new NPlotEngine.NPlotEngine(PlotEngineType.Synchronous);

                plot1.BackgroundColor = this.Control.Host.BackgroundColor;
                DataSet ds = new DataSet(original);
                ds.Label = original.Label;
                ds.Color = original.Color;
                plot1.AddDataSet(ds);
                plot1.Title = Catalog.GetString("Rawdata of the spectrum");
                plot1.XLabel = Catalog.GetString("Wavelength / nm");
                plot1.YLabel = Catalog.GetString("Absorbance");
                plot1.FitView();
                plot1.ProcessChanges();

                plot2.BackgroundColor = this.Control.Host.BackgroundColor;
                plot2.AddDataSet(backproj);
                plot2.Title = Catalog.GetString("Comparison of processed spectrum and database entry");
                if (this.IdentServerClient.IsTruePositive == true)
                    plot2.AddDataSet(matchbp);
                plot2.XLabel = Catalog.GetString("Wavelength / nm");
                plot2.YLabel = Catalog.GetString("f(Absorbance)");
                plot2.FitView();
                plot2.ProcessChanges();

                if (this.Config.Profiles.Current.ShowDifference == true && this.IdentServerClient.IsTruePositive)
                {
                    plot2.UseSecondAxes = true;
                    plot2.AddDataSet(difference);
                    double min = difference.YMin();
                    double max = difference.YMax();
                    plot2.YMin = min - 2 * (max - min);
                    plot2.YMax = max + 2 * (max - min);
                    plot2.ProcessChanges();
                    plot2.YLabel = Catalog.GetString("Difference*");
                    plot2.ProcessChanges();
                }

                HBox hbox = new HBox(true, 5);
                hbox.PackStart(plot1.GtkWidget, true, true, 0);
                hbox.PackStart(plot2.GtkWidget, true, true, 0);

                dialog.VBox.PackStart(hbox);
                hbox.ShowAll();

                dialog.IconList = ApoIdentStock.FinderIcons;

                dialog.Run();

                dialog.Destroy();

                ((IDisposable)plot1).Dispose();
                ((IDisposable)plot2).Dispose();
            }
            catch (Exception ex)
            {
                string message = String.Format(Catalog.GetString("Error during calculating the spectra: {0}"),
                                          ex.Message);
                this.Update(ApoIdentApplicationState.ShowErrorDialogWithServiceDialog, message);
                return;
            }
        }

        private void OnResultValuationButtonClicked(object sender, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                this.Update(ApoIdentApplicationState.ResultShowValuationList);
            }
        }

        private void ResultShowValuationList()
        {
            if (this.Control.CreateNotMeasurableReport == true)
            {
                string message = String.Format(Catalog.GetString("Ranking list is not available when a NIR inactive substance ist selected."));
                this.Update(ApoIdentApplicationState.ShowErrorDialogWithoutSerivceDialog, message);
                return;
            }

            try
            {
                ResultListDialog.Start(this.MainWindow,
                                 this.Config.Profiles.Current.ReportCountry,
                                 this.IdentServerClient.Result,
                                   this.GetProtocolTestId());
            }
            catch (Exception ex)
            {
                string message = String.Format(Catalog.GetString("Cannot show result list: {0}"),
                                          ex.Message);
                this.Update(ApoIdentApplicationState.ShowErrorDialogWithServiceDialog, message);
                return;
            }
        }

    }
}
