//
//  FinderSelftest.cs
//
// QuickStep: Acquire, view and identify spectra 
// Copyright (C) 2010-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.IO;

using Gtk;

using Hiperscan.Common.IO;
using Hiperscan.GtkExtensions.Widgets;
using Hiperscan.SGS;
using Hiperscan.SGS.Benchtop;
using Hiperscan.Unix;


namespace Hiperscan.Extensions.FinderSelftest
{

    internal static class FinderSelftest
    {

        public static void Start(IDevice dev)
        {
            string tmp_dir = string.Empty;

            try
            {
                Plugin.host.MainWindow.Sensitive = false;

                dev.CurrentConfig.Average = 500;
                dev.WriteConfig();
                Plugin.host.UpdateProperties();

                Finder finder = new Finder(dev, ReferenceWheelVersion.Auto, ExternalWhiteReferenceType.Zenith, Plugin.name)
                {
                    ExternalReferenceAveraging = 2000
                };

                tmp_dir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                tmp_dir = Path.Combine(tmp_dir, $"finder_selftest_{dev.Info.SerialNumber}_{DateTime.Now.ToString("yyyy-MM-dd_hh-mm")}");
                Directory.CreateDirectory(tmp_dir);

                finder.AutoSaveDirectory = tmp_dir;
                finder.AutoSaveReferences = true;

                finder.WaitForExternalWhiteReference += () =>
                {
                    FinderReferenceDialog.Run(Plugin.host.MainWindow, FinderReferenceType.ExternalWhiteZenith);
                    Plugin.host.ProcessEvents();
                };

                finder.WaitForExternalEmptyReference += () =>
                {
                    FinderReferenceDialog.Run(Plugin.host.MainWindow, FinderReferenceType.ExternalBlack);
                    Plugin.host.ProcessEvents();
                };

                FinderReferenceDialog.Run(Plugin.host.MainWindow, FinderReferenceType.ExternalWhiteZenith);
                Plugin.host.ProcessEvents();

                finder.Acquire(false);
                Plugin.host.ProcessEvents();
                finder.ResetRecalibrationTimestamp();
                finder.Acquire(false);
                Plugin.host.ProcessEvents();

                using (var chooser = new FileChooserDialog(Catalog.GetString("Specify archive name"),
                                                           Plugin.host.MainWindow,
                                                           FileChooserAction.Save,
                                                           Stock.Save, ResponseType.Ok,
                                                           Stock.Cancel, ResponseType.Cancel))
                {
                    FileFilter filter = new FileFilter
                    {
                        Name = Catalog.GetString("Archive")
                    };
                    filter.AddPattern("*.zip");
                
                    chooser.AddFilter(filter);
                    chooser.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                    chooser.CurrentName = $"selftest_{DateTime.Now.ToString("yyyy-MM-dd_HH-mm")}.zip";
                    chooser.DoOverwriteConfirmation = true;
                
                    chooser.ShowAll();
                    int choice = chooser.Run();
                    chooser.Hide();
                
                    if ((ResponseType)choice == ResponseType.Ok)
                    {
                        try
                        {
                            using (Zip zip = new Zip(chooser.Filename))
                            {
                                zip.AddDirectoryContent(Path.GetDirectoryName(tmp_dir)); 
                            }
                        }
                        catch (Exception ex)
                        {
                            Plugin.host.ShowInfoMessage(Plugin.host.MainWindow,
                                                        Catalog.GetString("Cannot export seftest spectra: {0}"), 
                                                         ex.Message);
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    if (string.IsNullOrEmpty(tmp_dir) == false && Directory.Exists(tmp_dir))
                        Directory.Delete(tmp_dir, true);
                }
#pragma warning disable RECS0022
                catch { }
#pragma warning restore RECS0022

                Plugin.host.MainWindow.Sensitive = true;
            }
        }
    }
}