// UI.DragNDrop.cs created with MonoDevelop
// User: klose at 13:20 16.03.2010
// CVS release: $Id: UI.DragNDrop.cs,v 1.6 2011-06-24 13:48:23 klose Exp $
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2010  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 System.IO;
using System.Text;

using Gtk;

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


namespace Hiperscan.QuickStep
{

    public partial class UserInterface
    {

        enum TargetType
        {
            Text,
            Uri
        }

        private static Gtk.TargetEntry[] TargetEntries = 
        {
            new TargetEntry("text/plain;charset=utf-8", 0, (uint)TargetType.Text), // DND from LibreOffice Calc
            new TargetEntry("string",                   0, (uint)TargetType.Text),
            new TargetEntry("text/plain",               0, (uint)TargetType.Text),
            new TargetEntry("text/uri-list",            0, (uint)TargetType.Uri)
        };

        private void OnDragDataReceived(object o, DragDataReceivedArgs e)
        {
            Console.WriteLine("OnDragDataReceived: {0}, {1}", (TargetType)e.Info, Encoding.UTF8.GetString(e.SelectionData.Data));

            bool first_iteration = true;
            bool changed = false;
            int plot_tab_page = this.plot_notebook.CurrentPage;

            string[] uri_strings = Encoding.UTF8.GetString(e.SelectionData.Data).Trim().Split('\n');
            double count = uri_strings.Length;
            Console.WriteLine("Opening {0} elements...", count);
            int ix = 0;

            foreach (string uri_string in uri_strings)
            {
                string trimmed_uri_string = uri_string.Trim(' ', '\n', '\r');

                if (string.IsNullOrEmpty(trimmed_uri_string) || string.IsNullOrWhiteSpace(trimmed_uri_string))
                    continue;

                Uri uri;
                try
                {
                    uri = new Uri(trimmed_uri_string);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Cannot convert URI string '{0}': {1}", trimmed_uri_string, ex.Message);
                    continue;
                }

                this.ShowProgress((double)(ix++) / count);

                try
                {
                    Spectrum[] spectra = new Spectrum[0];
                    List<MetaData> meta_data = null;
                    string fname = Uri.UnescapeDataString(uri.LocalPath);

                    if (Directory.Exists(fname))
                    {
                        this.AddFileTv(fname);
                        List<string> paths = Settings.Current.DataBrowserPaths;
                        paths.Add(fname);
                        Settings.Current.DataBrowserPaths = paths;
                        continue;
                    }

                    if (Path.GetExtension(fname).ToLower() == ".csv")
                    {
                        spectra = new Spectrum[] { CSV.Read(fname) };
                    }
                    else if (Path.GetExtension(fname).ToLower() == ".csvc")
                    {
                        spectra = CSV.ReadContainer(fname, out meta_data);
                    }
                    else
                    {
                        continue;
                    }

                    if (first_iteration)
                    {
                        this.plot_info_list.Current.CurrentSpectra.AddHistoryEntry();
                        first_iteration = false;
                    }

                    this.plot_notebook.CurrentPage = plot_tab_page;

                    for (int jx = 0; jx < spectra.Length; ++jx)
                    {
                        this.AddSpectrum(spectra[jx], false, false, true);
                    }

                    this.ScrolledPlot.RestoreAnnotations(meta_data);
                    changed = true;
                }
                catch (Exception ex)
                {
                    InfoMessageDialog.Show(this.MainWindow,
                                     Catalog.GetString("Error while reading file: {0}"),
                                     ex.Message);
                }
            }
            if (changed)
            {
                this.ScrolledPlot.Plot.RequestUpdate();
                this.CurrentSpectra.NotifyChanges();
            }
            if (this.PlotType.Interdependent)
                this.UpdateCurrentPlot();

            this.HideProgress();
        }
    }
}