// 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 Glade;

using Gtk;

using Hiperscan.Spectroscopy.IdentModule;
using Hiperscan.Unix;


namespace Hiperscan.Extensions.ApoIdent
{
    public class AdditionalTestWindow
    {
        private enum UpdateState
        {
            Init,
            TextChanged,
        }

        [Widget] Gtk.Window additional_test_window        = null;
        [Widget] Gtk.TextView additional_textview        = null;
        [Widget] Gtk.CheckButton identified_checkbutton    = null;
        [Widget] Gtk.Label final_result_label            = null;

        public static event EventHandler WindowClosed = null;

        public static AdditionalTestWindow Start(ApoIdentApplication apo_ident_app)
        {
            return new AdditionalTestWindow(apo_ident_app);
        }

        private AdditionalTestWindow (ApoIdentApplication apo_ident_app)
        {
            this.ParentWindow = apo_ident_app.MainWindow;
            this.CompletionEntries = apo_ident_app.Config.Profiles.Current.AdditionalCompletionEntries;

            string key = apo_ident_app.SubstanceManagement.CurrentSubstance.Id;
            this.CompletionEntries.LoadCustomerText(key);

            if (apo_ident_app.SubstanceManagement.CurrentSubstanceCategory != SubstanceCategory.NotMeasurable &&
                apo_ident_app.SubstanceManagement.CurrentSubstanceCategory != SubstanceCategory.UserDefined &&
                apo_ident_app.SubstanceManagement.CurrentSubstanceCategory != SubstanceCategory.Classifiaction &&
                apo_ident_app.IdentServerClient.IsTruePositive == true)
            {
                this.CompletionEntries.SubstanceUniqueIdentifed = true;
                this.CompletionEntries.CustomerIdentificationResult = true;
            } 

            Glade.XML gui = new Glade.XML(null, "ApoIdent.Resources.Glade.FinderWindow.glade", "additional_test_window", "Hiperscan");
            gui.Autoconnect(this);

            this.additional_test_window.SetWmclass(Plugin.name.ToLower(), 
                                                   Plugin.name.ToLower());

            this.additional_test_window.DefaultWidth = 300;
            this.additional_test_window.DefaultHeight =  600;
            this.additional_test_window.TransientFor = this.ParentWindow;

            string test = AdditionalTestEntries.LabelName(apo_ident_app).Replace("-\n", String.Empty);
            test = test.Replace("\n", " ").Replace("*", String.Empty);
            this.additional_test_window.Title = String.Format(Catalog.GetString("{0} (Method and Result)"), test);

            this.identified_checkbutton.Active = this.CompletionEntries.CustomerIdentificationResult;
            this.identified_checkbutton.Sensitive = this.CompletionEntries.SubstanceUniqueIdentifed == false;
            this.final_result_label.Sensitive = this.CompletionEntries.SubstanceUniqueIdentifed == false;
            this.additional_textview.Buffer.Text = this.CompletionEntries.CustomerText;

            this.Update(UpdateState.Init);

            this.additional_textview.Buffer.Changed += this.OnTextChanged;
            this.additional_test_window.DeleteEvent += this.OnAdditionalTestCloseButtonClicked;

            this.additional_test_window.ShowAll();
            this.additional_textview.GrabFocus();
        }

        private void OnTextChanged(object sender, EventArgs e)
        {
            this.Update(UpdateState.TextChanged);
        }
        
        private void OnAdditionalTestCloseButtonClicked(object sender, EventArgs e)
        {
            if (this.CompletionEntries.ProtocolText != this.additional_textview.Buffer.Text.Trim() ||
                this.CompletionEntries.CustomerIdentificationResult != this.identified_checkbutton.Active)
            {
                this.CompletionEntries.CustomerIdentificationResult = this.identified_checkbutton.Active;
                this.CompletionEntries.SetCustomerText(this.additional_textview.Buffer.Text);
                this.CompletionEntries.InsertIntoProtocol = true;
                this.CompletionEntries.Save();

                AdditionalTestWindow.WindowClosed?.Invoke(true, EventArgs.Empty);
            }
         
            this.additional_test_window.Destroy();


        }
        
        private void OnAdditionalTestCancelButtonClicked(object sender, EventArgs e)
        {
            bool changes = false;
            if (this.CompletionEntries.InsertIntoProtocol == true)
            {
                if (String.IsNullOrEmpty(this.CompletionEntries.CustomerText) == false ||
                    (this.CompletionEntries.CustomerIdentificationResult == true &&
                     this.CompletionEntries.SubstanceUniqueIdentifed == false))                   
                {
                    changes = true;
                }
                this.CompletionEntries.Reset();
                AdditionalTestWindow.WindowClosed?.Invoke(changes, EventArgs.Empty);
            }        
            this.additional_test_window.Destroy();
        }

        private void Update(UpdateState state)
        {
            switch(state)
            {
                case UpdateState.Init:
                case UpdateState.TextChanged:
                    bool has_text = String.IsNullOrEmpty(this.additional_textview.Buffer.Text.Trim()) == false;

                    this.identified_checkbutton.Sensitive = has_text && this.CompletionEntries.SubstanceUniqueIdentifed == false;
                    if (has_text == false && this.CompletionEntries.SubstanceUniqueIdentifed == false)
                    {
                        this.CompletionEntries.CustomerIdentificationResult = false;
                        this.identified_checkbutton.Active = false;
                    }
                    break;

                default:
                    break;
            }
        }

        private  AdditionalTestEntries CompletionEntries { get; set; }     
        private Gtk.Window ParentWindow  { get; set; }
    }
}

