// Dialogs.cs created with MonoDevelop
// User: klose at 18:10 12.03.2009
// CVS release: $Id: Dialogs.cs,v 1.25 2011-04-19 12:36:58 klose Exp $
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2009  Thomas Klose, 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 Gtk;

using Hiperscan.QuickStep.IO;
using Hiperscan.Spectroscopy.IO;
using Hiperscan.Unix;


namespace Hiperscan.QuickStep.Dialog
{

    public class FileChooserDialog : Gtk.FileChooserDialog
    {

        private readonly SpectrumPreviewWidget preview;
        private readonly ComboBox output_culture_combo;

        private static FileChooserDialog current_instance = null;

        private string current_name = string.Empty;
        private Dictionary<FileFilter,string> extensions = new Dictionary<FileFilter,string>();
        private FileFilter current_filter   = null;
        private static volatile bool running = true;


        public FileChooserDialog(string t, Window p, FileChooserAction a, params object[] b) : base(t, p, a)
        {
            FileChooserDialog.current_instance = this;
            
            this.TransientFor = p;
            this.IconList = MainClass.QuickStepIcons;
            
            this.preview = new SpectrumPreviewWidget();
            this.PreviewWidget = this.preview;
            
            if (a == FileChooserAction.Save)
            {
                this.ActionArea.PackStart(new Label(Catalog.GetString("Output culture:")));
                
                CellRendererText text = new CellRendererText();
                this.output_culture_combo = new ComboBox();
                this.output_culture_combo.PackStart(text, false);
                this.output_culture_combo.SetAttributes(text, "text", 0);
                this.output_culture_combo.Model = new ListStore(typeof(string));
                this.output_culture_combo.AppendText(Catalog.GetString("English"));
                this.output_culture_combo.AppendText(Catalog.GetString("German"));
                this.output_culture_combo.AppendText(Catalog.GetString("System"));
                this.output_culture_combo.Active = (int)MainWindow.UI.StandardOutputCulture;
                this.ActionArea.PackStart(this.output_culture_combo);
                this.ActionArea.PackStart(new Label(""));
            }

            if (b.Length % 2 != 0)
                throw new ArgumentException("Invalid argument count.");
            
            for (int ix=0; ix < b.Length; ix += 2)
            {
                this.AddButton((string)b[ix], (ResponseType)b[ix+1]);
            }
            
            this.SelectionChanged += this.OnSelectionChanged;
            
            FileChooserDialog.running = true;
            GLib.Timeout.Add(100, FileChooserDialog.UpdateCurrentName);
            
            this.ShowAll();
        }
        
        private static bool UpdateCurrentName()
        {
            try
            {
                if (current_instance == null ||
                    string.IsNullOrEmpty(current_instance.current_name))
                    return false;
                if (FileChooserDialog.running == false)
                    return false;
                if (current_instance.current_filter == current_instance.Filter)
                    return true;
                if (!current_instance.extensions.ContainsKey(current_instance.Filter))
                    return true;
                if (string.IsNullOrEmpty(current_instance.current_name))
                    return true;
                string ext = current_instance.extensions[current_instance.Filter];
                string name = System.IO.Path.GetFileNameWithoutExtension(current_instance.current_name);
                if (System.IO.Path.GetFileName(current_instance.Filename) == $"{name}.{ext}")
                    return true;
                current_instance.CurrentName = $"{name}.{ext}";
                current_instance.current_filter = current_instance.Filter;
                // reset folder to select filename without extension
                current_instance.SetCurrentFolder(current_instance.CurrentFolder);
                return true;
            }
            catch (ArgumentNullException)
            {
                // dialog may already be destroyed
                return false;
            }
        }
        
        public int _Run()
        {
            int response = this.Run();
            FileChooserDialog.running = false;
            return response;
        }

        private void OnSelectionChanged(object o, EventArgs e)
        {
            try
            {
                if (System.IO.Path.GetExtension(this.PreviewFilename).ToLower() == ".csv")
                {
                    this.preview.Spectrum = CSV.Read(this.PreviewFilename);
                    this.PreviewWidgetActive = true;
                }
                else if (System.IO.Path.GetExtension(this.PreviewFilename).ToLower() == ".csvc")
                {
                    this.preview.Spectra = CSV.ReadContainer(this.PreviewFilename);
                    this.PreviewWidgetActive = true;
                }
                else
                {
                    this.PreviewWidgetActive = false;
                }
            }
            catch
            { 
                this.PreviewWidgetActive = false;
            }
        }
        
        public void AddFilter(FileFilter filter, string extension)
        {
            this.AddFilter(filter);
            this.extensions.Add(filter, extension);
        }
        
        public string _CurrentName 
        {
            set 
            {
                this.current_name = value;
                this.CurrentName  = value;
            }
        }
        
        public OutputCulture OutputCulture
        {
            get { return (OutputCulture)this.output_culture_combo.Active; }
            set { this.output_culture_combo.Active = (int)value;          }
        }
    }
}