// 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.IO;
using Gtk;

using Hiperscan.Unix;


namespace Hiperscan.Extensions.ApoIdent
{
    public partial class ApoIdentApplication
    {
        private void ShowPreSelectionArchive(object sender)
        {
            switch (this.Config.Profiles.AllProfiles.Count)
            {

            case 0:
                    this.Control.Host.ShowInfoMessage(this.main_window,
                    Catalog.GetString("There isn't any profile for showing the archive."));
                break;

            case 1: 
                    if (Directory.Exists(this.Config.Profiles.Current.Archive) == true)
                        this.Control.Host.OpenFileBrowser(this.Config.Profiles.Current.Archive);    
                else
                        this.ShowMissingArchiveDirectoryMessage(this.Config.Profiles.Current.Archive);
                break;

            default:
                this.CreateArchiveContextMenu(sender);    
                break;

            }
        }

        private void CreateArchiveContextMenu(object sender)
        {
            if (this.MainWindow.GdkWindow == null)
                return;

            Menu archive_menu = new Menu();

            foreach (Configurations.ProfilePreferences profile in this.Config.Profiles.AllProfiles.Values)
            {
                MenuItem item = new MenuItem(profile.Name);
                item.Activated += this.OnArchivePreSelectionActivated;
                item.Data["archive"] = profile.Archive;
                archive_menu.Append(item);
            }

            ToolButton archive_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;

            archive_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 + archive_tool_button.Allocation.Height;

            Hiperscan.GtkExtensions.Widgets.Font.SetFont(archive_menu, ApoIdentApplication.FONT_FAMILIY);

            archive_menu.ShowAll();
            archive_menu.Popup();

            Gtk.Window parent_window = (Gtk.Window)archive_menu.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 - archive_tool_button.Allocation.Height - parent_window.Allocation.Height;
            
            parent_window.Move(x, y);
        }

        private void OnArchivePreSelectionActivated(object sender, EventArgs e)
        {
            MenuItem menu_item = sender as MenuItem;
            string archive = (string) menu_item.Data["archive"];

            if (Directory.Exists(archive) == true)
                this.Control.Host.OpenFileBrowser(archive);    
            else
                this.ShowMissingArchiveDirectoryMessage(archive);
        }

        private void ShowMissingArchiveDirectoryMessage(string path)
        {
            this.Control.Host.ShowInfoMessage(this.MainWindow,
                Catalog.GetString("An archive directory with path '{0}' does not exist."),
                path);
        }

        public void CheckArchive()
        {
            if (this.Config.Profiles.Current == null)
                return;

            if (this.Config.Profiles.Current.ArchiveMissing == false)
                return;

            string message = String.Format(Catalog.GetString(
               "The Apo-Ident archive directory \"{0}\" for configuration profile \"{1}\" is unavailable. " +
               "This may be a temporary problem with a network resource or removable storage device.\n\n" +
               "- You can create a new archive in the <i>settings -> report settings</i>\n" +
               "- or you close this application and restore the archive and restart the software.\n\n" +
                "If you continue anyway, all data for this profile of this session will be get lost after closing application."),
                                    this.Config.Profiles.Current.Archive, 
                                    this.Config.Profiles.Current.Name);           ;
                                    
            this.Update(ApoIdentApplicationState.ShowErrorDialogWithoutSerivceDialog, message);
        }

        private void CheckMissingArchive(Configurations.ProfilePreferences profile)
        {
            try
            {
                profile.ArchiveMissing = Directory.Exists(profile.Archive) == false;
            }
            catch (Exception)
            {
                profile.ArchiveMissing = true;
            }
        }

        private void CreateArchive(Configurations.ProfilePreferences profile)
        {
            if (this.Config.Profiles.Current == null)
                return;

            Configurations.ProfilePreferences current = this.Config.Profiles.Current;

            profile.ArchiveMissing = false;
            this.Config.Profiles.Current = profile;

            try
            {
                if (Directory.Exists(FilesAndDirs.Archive) == false)
                    Directory.CreateDirectory(FilesAndDirs.Archive);

                if (File.Exists(FilesAndDirs.AdditionalTestAutoCompletionFile) ||
                                File.Exists(FilesAndDirs.AdditionalTestAutoCompletionBackupFile) ||
                                profile.AdditionalCompletionEntries == null)
                {
                    this.Config.Profiles.Current.ReadAddtionalInfos();
                }

                profile.AdditionalCompletionEntries.Save();

                if (File.Exists(FilesAndDirs.ModelClassExtensionFile) ||
                    File.Exists(FilesAndDirs.ModelClassExtensionBackupFile) ||
                    profile.SubstanceExtension == null)
                {
                    this.Config.Profiles.Current.ReadNotMeasurableSubstances(this.IdentServerClient);
                }

                profile.SubstanceExtension.Save(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot create archive '{0}': {1}", FilesAndDirs.Archive, ex);
            }

            this.Config.Profiles.Current = current;
        }

    }
}

