// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2017 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 System.Collections.Generic;
using System.Threading;

using Glade;
using Hiperscan.AnalysisModule;
using Hiperscan.ApoIdentCore;
using Hiperscan.ApoIdentCore.SectionManager.Substance;
using Hiperscan.Pdf.MergedSubstances;
using Hiperscan.Unix;

namespace Hiperscan.Extensions.ApoIdent
{
    public class SubstanceClassificationInfoDialog
    {
        [Widget] Gtk.Window not_separable_window = null;
        [Widget] Gtk.Label text_label1 = null;
        [Widget] Gtk.Label text_label2 = null;
        [Widget] Gtk.TreeView substances_treeview = null;
        [Widget] Gtk.Button close_button = null;

        public static SubstanceClassificationInfoDialog Run(Gtk.Window parent,AppControl control)
        {
            return new SubstanceClassificationInfoDialog(parent, control.SubstanceManager);
        }

        private SubstanceClassificationInfoDialog(Gtk.Window parent, SubstanceManager substance_manager)
        {
            this.SubstanceManager = substance_manager;
            this.NamePairs = this.SubstanceManager.SubstancesCatalog.Classification.GetSubstanceNames(this.SubstanceManager.SubstancesCatalog.Substance);

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

            ApoIdent.ApoIdentApplication.SetWmcClassName(this.not_separable_window);

            this.not_separable_window.TransientFor = parent;


            this.not_separable_window.Title = Catalog.GetString("Substance not conclusively distinguishable");
            this.Text1 = String.Format(Catalog.GetString("The selected substance '{0}' is not conclusively distinguishable by near-infrared spectroscopy (Apo-Ident) from following substances:"),
                                       this.SubstanceManager.SubstancesCatalog.SelectedSubstanceName);

            this.text_label1.Text = this.Text1;

            this.Text2 = String.Format(Catalog.GetString(
"Apo-Ident combines these substances in the classification '{0}'. In order to get a conclusive test result, additional tests are necessary to distinguish within this classification."
                    ), this.SubstanceManager.SubstancesCatalog.Classification.Name);

            this.text_label2.Text = this.Text2;

            this.InitTreeview();

            GuiDesigner.SetSchema(this.not_separable_window);
            this.not_separable_window.ShowAll();
            this.close_button.GrabFocus();
        }

        private void InitTreeview()
        {
            Gtk.TreeViewColumn german_column = new Gtk.TreeViewColumn();
            german_column.Title = Catalog.GetString("Substance name");
            german_column.Alignment = 0.5f;
            german_column.Expand = true;

            Gtk.CellRendererText german_cell = new Gtk.CellRendererText();
            german_cell.Xpad = 5;
            german_column.PackStart(german_cell, true);


            Gtk.TreeViewColumn latin_column = new Gtk.TreeViewColumn();
            latin_column.Title = Catalog.GetString("Latin name");
            latin_column.Alignment = 0.5f;
            latin_column.Expand = true;

            Gtk.CellRendererText latin_cell = new Gtk.CellRendererText();
            latin_cell.Xpad = 5;
            latin_column.PackStart(latin_cell, true);

            this.substances_treeview.AppendColumn(german_column);
            this.substances_treeview.AppendColumn(latin_column);

            german_column.AddAttribute(german_cell, "text", 0);
            latin_column.AddAttribute(latin_cell, "text", 1);

            Gtk.ListStore store = new Gtk.ListStore(typeof(string), typeof(string));
            this.substances_treeview.Model = store;


            MergedList list = new MergedList();


            foreach (string default_name in this.NamePairs.Keys)
            {
                SummarizedEntry entry = new SummarizedEntry();
                entry.DefaultNames.Add(default_name);
                entry.LatinNames.Add(this.NamePairs[default_name]);
                list.Entries.Add(entry);
            }
            list.Sort();

            foreach (SummarizedEntry entry in list.Entries)
                store.AppendValues(entry.DefaultNames[0], entry.LatinNames[0]);

        }

        private void OnCloseButtonClicked(object sender, EventArgs e)
        {
            this.not_separable_window.Destroy();
        }

        private void CallDeleteTempFile(string file)
        {
            try
            {
                ParameterizedThreadStart pts = new ParameterizedThreadStart(this.DeleteTempFile);
                Thread t = new Thread(pts);
                t.Start(file);
            }
            catch (Exception) { }
        }

        private void DeleteTempFile(object file)
        {
            Thread.Sleep(5000);
            FileIO.DeleteFile((string)file, true);
        }

        private void OnClassificationInfoLinkButtonClicked(object sender, EventArgs e)
        {
            try
            {
                MergedList list = new MergedList();

                foreach (string default_name in this.NamePairs.Keys)
                {
                    SummarizedEntry entry = new SummarizedEntry();
                    entry.DefaultNames.Add(default_name);
                    entry.LatinNames.Add(this.NamePairs[default_name]);
                    list.Entries.Add(entry);
                }
                list.Sort();
                list.ClassName = this.SubstanceManager.SubstancesCatalog.ModelClass.Name;
                list.Version = String.Format(Catalog.GetString("IdentModule: {0}"), this.SubstanceManager.GetServerInfo(AnalysisType.Identification).Version.ModuleVersion);
                list.Text1 = this.Text1;
                list.Text2 = this.Text2;
                this.PdfFile = MergedCreator.PdfTmpFile;
                MergedCreator.Create(list, this.PdfFile);
                Process.OpenUri(this.PdfFile);
                this.CallDeleteTempFile(this.PdfFile);
            }
            catch (Exception ex)
            {
                string message = String.Format(Catalog.GetString("Cannot open substance classification overview: {0}"), ex.Message);
                Gtk.MessageDialog mdlg = new Gtk.MessageDialog(this.not_separable_window,
                                                                      Gtk.DialogFlags.Modal,
                                                                      Gtk.MessageType.Error,
                                                                      Gtk.ButtonsType.Ok,
                                                                      message);

                mdlg.IconList = ApoIdentStock.FinderIcons;
                mdlg.Run();
                mdlg.Destroy();
                Console.WriteLine(message);
            }
        }

        private string Text1 { get; set; }
        private string Text2 { get; set; }
        private SubstanceManager SubstanceManager { get; set; }
        private Dictionary<string, string> NamePairs { get; set; }
        private string PdfFile { get; set; }
    }
}

