// 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.Collections.Generic;
using System.Reflection;
using Gtk;
using Hiperscan.Extensions.ApoIdent.Widgets;
using Hiperscan.Unix;

namespace Hiperscan.Extensions.ApoIdent
{
    public partial class ApoIdentApplication
    {
        private void OnQuickStepMenuButtonClicked(object o, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                if (this.Control.Host.MainWindow == null)
                    return;

                if (this.Control.Host.MainWindow.Visible == false)
                {
                    bool dont_show_again = this.Config.GuiSettings.DontShowQuickStepMessageAgain;
                    this.Control.Host.ShowInfoMessage(this.main_window, ref dont_show_again,
                                              Catalog.GetString("In Quickstep-mode (advanced mode) parameters of the spectrometer can be modified. " +
                                                                "This possibly leads to incorrect measurements or identifications.")
                                              );
                    this.Config.GuiSettings.DontShowQuickStepMessageAgain = dont_show_again;
                }
            }

            this.Control.Host.MainWindow.ShowAll();
            this.Control.Host.MainWindow.Present();
        }

        private void OnExitMenuButtonClicked(object o, EventArgs e)
        {
            this.Exit();
        }


        private void OnArchiveMenuButtonClicked(object sender, EventArgs e)
        {
            this.ShowPreSelectionArchive(sender);
        }

        private void OnQueryMenuButtonClicked(object o, EventArgs e)
        {
            this.Update(ApoIdentApplicationState.QueryDialog);
        }

        private void OnResetReferenceMenuButtonClicked(object o, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                try
                {
                    this.Finder.ResetReferences();
                    this.Finder.MeasuringState = this.Finder.GetMeasuringState(this.SubstanceManagement);
                    if (this.Finder.MeasuringState != MeasuringState.None)
                    {
                        if (this.Control.MeasuringProgressState.IsAcquiringFirstFluid)
                        {
                            this.Control.MeasuringProgressState.ResetFlags();
                            this.Update(ApoIdentApplicationState.SubstanceManagementSubstanceAfterSelectionChanged);
                        }
                        else
                        {
                            this.Update(ApoIdentApplicationState.MeasuringEndInternalCaibration);
                        }
                    }
                    else
                    {
                        this.Update(ApoIdentApplicationState.MeasuringReferencesReset);
                    }
                }
                catch(Exception ex)
                {
                    if (this.Control.IsDisconnecting == false)
                        Console.WriteLine("Cannot reset references: {0}", ex);
                }
            }
        }

        private void OnSettingsMenuButtonClicked(object o, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                if (this.CheckForNotSavedProtocolDetails() == false)
                    return;
            }

            if (this.Control.IsDisconnecting)
                return;

            this.SubstanceManagement.ResetSelection();
            this.Update(ApoIdentApplicationState.PreferencesDialog);
        }

        private void OnConnectMenuButtonClicked(object o, EventArgs e)
        {
            System.Threading.Tasks.Task.Run(() => this.InitConnection());
        }

        private void OnSubstanceManagementMenuButtonClicked(object sender, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                if (this.CheckForNotSavedProtocolDetails() == false)
                    return;
            }

            if (this.Control.IsDisconnecting || this.Control.ConnectionIsInitializing)
                return;

            this.SubstanceManagement.ResetSelection();
            this.Update(ApoIdentApplicationState.SubstancesDialog);

            if (this.Control.IsDisconnecting || this.Control.ConnectionIsInitializing)
                return;

            this.SubstanceManagement.InitModelExtension();
            this.Update(ApoIdentApplicationState.SubstanceManagementReinit);
        }

        private void OnHelpMenuButtonClicked(object sender, EventArgs e)
        {
            if (this.MainWindow.GdkWindow == null)
                return;

            ToolButton help_tool_button = sender as ToolButton;

            int screen_x = this.main_window.Screen.Width;
            int screen_y = this.main_window.Screen.Height;

            int x = 0;
            int y = 0;

            help_tool_button.TranslateCoordinates(this.main_window, 0, 0, out x, out y);

            int tmp_x;
            int tmp_y;

            this.MainWindow.GdkWindow.GetPosition(out tmp_x, out tmp_y);
            x += tmp_x;
            y += tmp_y + help_tool_button.Allocation.Height;

            this.HelpMenu.Popup();
            this.HelpMenu.ShowAll();

            Gtk.Window parent_window = (Gtk.Window)this.HelpMenu.Parent;

            if (x + parent_window.Allocation.Width > screen_x)
                x = screen_x - parent_window.Allocation.Width;

            if (y + parent_window.Allocation.Height > screen_y)
                y = y - help_tool_button.Allocation.Height - parent_window.Allocation.Height;

            parent_window.Move(x, y);
        }

        internal void OnInfoMenuButtonClicked(object o, EventArgs e)
        {
            lock (this.Control.Transaction)
            {
                AboutDialog dialog = new AboutDialog();
                dialog.TransientFor = this.main_window;

                dialog.ProgramName = "QuickStep " + Plugin.name;

                dialog.Version = Plugin.version;
                dialog.Comments = string.Format(Catalog.GetString("Chemometrics Plugin for QuickStep"));

                if (String.IsNullOrEmpty(this.Config.IdentModuleSettings.IdentServerVersion) == false)
                {
                    string version = this.Config.IdentModuleSettings.IdentServerVersion + "-" +
                                         this.Config.IdentModuleSettings.IdentServerSuffix;

                    Gtk.VBox vbox_tmp = ((Gtk.VBox)dialog.VBox.Children[0]);
                    List<Widget> widgets = new List<Widget>(vbox_tmp.Children);
                    foreach (Widget widget in widgets)
                        vbox_tmp.Remove(widget);


                    string server_label_text = Catalog.GetString("Ident-Modul Version: ");
                    if (IdentServerClient.CanConnectToIdentModule == false)
                        server_label_text += Catalog.GetString("Not installed");
                    else
                        server_label_text += version;

                    LinkButton ident_server_lb = new LinkButton("", server_label_text);
                    ident_server_lb.TooltipText = Catalog.GetString("IdentModule license text");

                    Gtk.Label comment_extenison_label = new Gtk.Label(Catalog.GetString("White reference: ") + "Zenith");

                    if (this.Finder != null && this.Finder.DeviceExists)
                    {
                        comment_extenison_label.Text += "\n";
                        comment_extenison_label.Text += String.Format(Catalog.GetString("Product: {0}"),
                                                                      this.Finder.ProductName);

                        comment_extenison_label.Text += "\n";
                        comment_extenison_label.Text += String.Format(Catalog.GetString("Connection: {0}"),
                                                                      this.Finder.ConnectionType);
                        if (this.Finder.Device.Info.IsRemote == true)
                        {
                            comment_extenison_label.Text += String.Format(" - {0}",
                                                                          this.Finder.RemoteDeviceServerAddress);

                        }

                        comment_extenison_label.Text += "\n";
                        comment_extenison_label.Text += String.Format(Catalog.GetString("Serial number: {0}"),
                                                                      this.Finder.Serial);
                    }

                    comment_extenison_label.Text += "\n\n" + Catalog.GetString("kundenservice@apo-ident.de\n+49 (0)351 212 496 33");
                    comment_extenison_label.Justify = Justification.Center;

                    Gtk.Alignment add_align = new Alignment(0.5f, 0.5f, 0f, 0f);
                    add_align.Add(ident_server_lb);
                    VBox add_vbox = new VBox();
                    add_vbox.Add(add_align);
                    add_vbox.Add(comment_extenison_label);

                    widgets.Insert(3, add_vbox);

                    foreach (Widget widget in widgets)
                        vbox_tmp.Add(widget);

                    ident_server_lb.Clicked += (sender, evnt) => IdentServerClient.LicenseDialog.Start(dialog, this.Config);
                }
                else
                {
                    dialog.Comments += Catalog.GetString("\nWhite reference: ") + "Zenith";


                    dialog.Comments += "\n\n" + Catalog.GetString("kundenservice@apo-ident.de\n+49 (0)351 212 496 33");
                }

                dialog.Copyright = String.Format("2010-{0}, HiperScan GmbH", Plugin.copyright_year);

                dialog.WrapLicense = true;
                dialog.License = Catalog.GetString(Plugin.license);
                dialog.Authors = Plugin.authors;

                dialog.Website = Uris.OnlineHelp(ReferrerId.TeamViewer, true);
                dialog.WebsiteLabel = Catalog.GetString("Service Center");
                dialog.Logo = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "ApoIdent.Resources.Images.logo.png");

                try
                {
                    Widget w = dialog.ActionArea.Children[2];
                    dialog.ActionArea.Remove(w);

                    LinkButton lb = new LinkButton("file:///usr/lib/identserver/update-certificate.pdf", Catalog.GetString("Certificate"));
                    lb.Clicked += delegate (object sender, EventArgs ee)
                    {
                        try
                        {
                            this.SubstanceManagement.Pdfs.ShowUpdateCertificatePdf();
                        }
                        catch (Exception ex)
                        {
                            this.Control.Host.ShowInfoMessage(dialog,
                                                      Catalog.GetString("Cannot open ULR '{0}': {1}"),
                                                      FilesAndDirs.UpdateCertificateFile, ex.Message);
                        }
                    };
                    lb.TooltipText = Catalog.GetString("Open update certificate");
                    dialog.ActionArea.Add(lb);
                    dialog.ActionArea.Add(w);
                }
                catch (Exception)
                {

                }

                dialog.IconName = Stock.About;
                Hiperscan.GtkExtensions.Widgets.Font.SetFont(dialog, ApoIdentApplication.FONT_FAMILIY);
                dialog.ShowAll();
                dialog.Run();
                dialog.Destroy();
            }
        }
    }
}
