// 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.IO;
using System.Diagnostics;
using System.Threading;
using Glade;

using Hiperscan.Unix;
using Hiperscan.Pdf.MergedSubstances;


namespace Hiperscan.Extensions.ApoIdent
{
	public class ClassificationInfoWindow
	{
		[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 ClassificationInfoWindow(Gtk.Window parent, SubstanceManagement substance_db, bool show_only_pdf)
		{
            this.SubstanceManagement = substance_db;
            this.NamePairs   = this.SubstanceManagement.CurrentClassification.GetSubstanceNames(this.SubstanceManagement.CurrentSubstance);

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


            this.not_separable_window.TransientFor = parent;
                

			this.not_separable_window.Title = Catalog.GetString("Substance Not Definitely Separable");
			this.Text1 = String.Format(Catalog.GetString("The selected substance '{0}' is not " +
			                                                        "definitely separable by NIR (Apo-Ident) " + 
			                                                        "to following substances:"), 
                                       this.SubstanceManagement.CurrentSubstance.SelectedDefaultName);

			this.text_label1.Text = this.Text1;

			this.Text2 = String.Format(Catalog.GetString("Apo-Ident summarized these substances to the classification '{0}'. " +
			                                                        "In order to get a definite result, an additional test is nessecary within this classification,"), 
                                       this.SubstanceManagement.CurrentClassification.ClassificationName);

			this.text_label2.Text = this.Text2;
			
			if (show_only_pdf == true)
			{
				this.OnClassificationInfoLinkButtonClicked(null, null);
				Thread.Sleep(1000);
				this.OnCloseButtonClicked(null, null);
			}
			else
			{
			
				this.InitTreeview();

				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)
		{
			try
			{		
				Thread.Sleep(5000);
				File.Delete((string)file);
			}
			catch (Exception)
			{
			}
		}

		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.SubstanceManagement.CurrentModelClass.ModelClassName;
				list.Version 	= String.Format(Catalog.GetString("IdentModule: {0}"), IdentServerClient.Info.ShortIdentModuleVersion);
				list.Text1 		= this.Text1;
				list.Text2		= this.Text2;
				this.PdfFile	= MergedCreator.PdfTmpFile;
				MergedCreator.Create(list, this.PdfFile);
                System.Diagnostics.Process.Start(this.PdfFile);
				this.CallDeleteTempFile(this.PdfFile);
			}
			catch(Exception ex)
			{
				string message = String.Format(Catalog.GetString("Error while showing summarized substances: {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 SubstanceManagement SubstanceManagement {get; set;}
        private Dictionary<string,string> NamePairs     {get; set;}
		private string PdfFile					        {get; set;}
	}
}

