// 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 Gtk;
using Glade;
using Hiperscan.Spectroscopy;
using Hiperscan.Unix;
using Hiperscan.I18n;

namespace Hiperscan.Extensions.ApoIdent
{
    public partial class FinderWindow
    {
        [Widget] Gtk.Alignment substance_align_lhs          = null;
        [Widget] Gtk.Alignment substance_align_rhs          = null;
        [Widget] Gtk.Alignment data_exchange_alignment      = null;

        [Widget] Gtk.Button substance_search_label_button   = null;
        [Widget] Gtk.Button class_label_button              = null;
        [Widget] Gtk.Button substance_name_label_button     = null;
        [Widget] Gtk.Button latin_name_label_button         = null;

        [Widget] Gtk.Entry substance_search_entry           = null;
        [Widget] Gtk.Label class_label                      = null;   
        [Widget] Gtk.Label substance_name_label             = null;
        [Widget] Gtk.Label latin_name__label                = null;
       
        [Widget] Gtk.Button data_exchange_button            = null;
        [Widget] Gtk.Button substance_category_button       = null;
        [Widget] Gtk.Image data_exchange_image              = null;
        [Widget] Gtk.Image substance_category_image         = null; 
        [Widget] Gtk.Button class_button                    = null;

        private void UpdateSubstanceSection(bool update_substance_entries)
        {
            bool section_is_active = this.InitState == ServerDeviceState.Success;
            this.substance_align_lhs.Sensitive = section_is_active; 
            this.substance_align_rhs.Sensitive = section_is_active;

            this.SetButtonStyle(WindowSections.SubstanceSection, section_is_active);

            if (update_substance_entries == true)
                this.UpdateSubstanceEntries();

            this.SetSubstanceSearchEntryColor();
            this.SetSubstanceCategoryButton();
            this.SetDataExchangeButton();
            this.SetModelClassButton();
            this.SetModelClassLabel();
            this.SetSubstanceNameLabel();
            this.SetLatinNameLabel();
        }

        private void UpdateSubstanceEntries()
        {
            this.substance_search_entry.Text = String.Empty;  
            ListStore specimen_store        = (ListStore)this.substance_search_entry.Completion.Model;
            specimen_store.Clear();

            if (this.InitState != ServerDeviceState.Success)
                return;
            
            Gtk.Label  label = new Gtk.Label();
            int max = 0;

            foreach (SubstanceListAutoCompletionEntry  substance_entry in this.SubstanceManagement.GetAllSubstanceNames())
            {
                specimen_store.AppendValues(substance_entry.SubstanceCategory, substance_entry.Name, substance_entry);
                label.Text = substance_entry.Name;
                int width = label.SizeRequest().Width;
                if (width > max)
                    max = width;
            }

            foreach (string model_class in this.SubstanceManagement.ModelClassNameDetailResolver.Keys)
            {
                label.Text = model_class;
                int width = label.SizeRequest().Width;
                if (width > max)
                    max = width;
            }

            this.substance_search_entry.WidthRequest = max + 60;
        }

        private void SetModelClassLabel()
        {
            if (this.SubstanceManagement.IsLoadingStarted == true)
                this.class_label.Text = Catalog.GetString("Waiting for Ident Module ...");
            else if (this.InitState != ServerDeviceState.Success)
                this.class_label.Text = Catalog.GetString("Models not available.");
            else
                this.class_label.Text = this.SubstanceManagement.CurrentModelClass?.ModelClassName ?? String.Empty;
        }

        private void SetSubstanceNameLabel()
        {
            this.substance_name_label.Text = this.SubstanceManagement.CurrentSubstance?.SelectedDefaultName;
        }

        private void SetLatinNameLabel()
        {
            if (this.SubstanceManagement.CurrentSubstance == null)
            {
                this.latin_name__label.Text = String.Empty;
            }
            else if (String.IsNullOrEmpty(this.SubstanceManagement.CurrentSubstance.SelectedLatinName) == true)
            {
                this.latin_name__label.Text = SubstanceManagement.LocalizedNotAvailable;
            }
            else
            {
                this.latin_name__label.Text = this.SubstanceManagement.CurrentSubstance.SelectedLatinName;
            }
        }


        private bool MatchSpecimen(EntryCompletion completion, string key, TreeIter iter)
        {
            if (key == " ")
                return true;

            key = key.ToLower().Trim();
            key = key.Replace(",", String.Empty);
            key = key.Replace(";", String.Empty);
            key = key.Replace("-", String.Empty);
            key = key.Replace(".", String.Empty);
            key = key.Replace("\u0061\u0308", "\u00e4");
            key = key.Replace("\u006f\u0308", "\u00f6");
            key = key.Replace("\u0075\u0308", "\u00fc");

            TreeModel store = completion.Model;
            string line = (((string)store.GetValue(iter, 1)) ?? String.Empty).Trim().ToLower();
            line = line.Replace(",", String.Empty);
            line = line.Replace(";", String.Empty);
            line = line.Replace("-", String.Empty);
            line = line.Replace(".", String.Empty);
            line = line.Replace("ß", "ss");

            if (key.Length < 4)
            {
                if (line.StartsWith(key) == true)
                    return true;

                string[] line_data = line.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
                int count = 0;
                foreach(string sub_line in line_data)
                {
                    if (sub_line.StartsWith(key) == true)
                        count++;
                }
                if (count == line_data.Length)
                    return true;
            }
            else
            {
                if (line.Contains(key) == true)
                    return true;
            }
            return false;
        }

        private void SetSubstanceSearchEntryColor()
        {
            switch (SubstanceListAutoCompletionEntry.ConvertToSubstanceCategory(this.SubstanceManagement.CurrentClassification))
            {
                case SubstanceCategory.SingleSubstance:
                    this.substance_search_entry.ModifyBase(StateType.Normal, this.MeasurableColor);
                    break;

                case SubstanceCategory.Classifiaction:
                    this.substance_search_entry.ModifyBase(StateType.Normal, this.ClassificationColor);
                    break;

                case SubstanceCategory.NotMeasurable:
                    this.substance_search_entry.ModifyBase(StateType.Normal, this.NotMeasurableColor);
                    break;

                case SubstanceCategory.UserDefined:
                    this.substance_search_entry.ModifyBase(StateType.Normal, this.UserDefinedColor);
                    break;

                default:
                    this.substance_search_entry.ModifyBase(StateType.Normal, this.DefaultEntryBgColor);
                    break;
            }
        }       

        private void SetSubstanceCategoryButton()
        {
            switch (SubstanceListAutoCompletionEntry.ConvertToSubstanceCategory(this.SubstanceManagement.CurrentClassification))
            {
                case SubstanceCategory.None:
                    this.substance_category_button.Visible = false;
                    break;

                case SubstanceCategory.SingleSubstance:
                    this.substance_category_button.Visible = false;
                    break;

                case SubstanceCategory.Classifiaction:
                    this.substance_category_image.Stock = Stock.DialogWarning;
                    this.substance_category_button.Visible = true;
                    break;

                case SubstanceCategory.NotMeasurable:
                    this.substance_category_image.Stock = Stock.Info;
                    this.substance_category_button.Visible = true;
                    break;

                case SubstanceCategory.UserDefined:
                    this.substance_category_image.Stock = Stock.Info;
                    this.substance_category_button.Visible = true;
                    break;     

                default:
                    break;
            }
        }

        private void SetDataExchangeButton()
        {           
            this.data_exchange_button.Visible = this.Config.Profiles.Current != null    && 
                this.Config.Profiles.Current.ExchangeData.IsActivated == true           &&
                Locale.Language == "de";

            if (this.data_exchange_button.Visible == false)
                return;

            switch(this.Config.Profiles.Current.ExchangeData.ProtocolType)
            {

                case ProtocolType.Lennartz:
                    this.data_exchange_button.TooltipText = Catalog.GetString("Import data for laboratory program 'Dr. Lennartz'");;

                    if (this.SubstanceManagement.ProtocolCompletion == ProtocolAutoCompletionType.ThirdParty)
						this.data_exchange_image.Stock = ApoIdentStock.LENNARTZ_OK;
                    else
						this.data_exchange_image.Stock = ApoIdentStock.LENNARTZ;
                    break;

                default:
                    this.data_exchange_button.TooltipText = string.Empty;

                    if (this.SubstanceManagement.ProtocolCompletion == ProtocolAutoCompletionType.ThirdParty)
                        this.data_exchange_image.Stock = Stock.Apply;
                    else
                        this.data_exchange_image.Stock = Stock.Refresh;

                    break;
            }
        }

        private void SetModelClassButton()
        {
            this.class_button.Visible = this.SubstanceManagement.CurrentSubstance != null &&
                this.SubstanceManagement.GetModelClasses(this.SubstanceManagement.CurrentSubstance.SelectedName).Count > 1;            
        }

        private Gdk.Color DefaultEntryBgColor   {get; set;}
        private Gdk.Color ClassificationColor   {get; set;}
        private Gdk.Color NotMeasurableColor    {get; set;}
        private Gdk.Color MeasurableColor       {get; set;}
        private Gdk.Color UserDefinedColor      {get; set;}
    }
}
