// ThumbnailProvider.cs created with MonoDevelop
// User: klose at 20:34 22.06.2010
// CVS release: $Id: ThumbnailProvider.cs,v 1.3 2011-04-19 12:41:54 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.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG;
using System.Drawing;
using System.IO;
using System.Collections.Generic;

using Hiperscan.FileIO;
using Hiperscan.Spectroscopy;


namespace Hiperscan
{
	
    [ComVisible(true)]
    [Guid("e357fccd-a995-4576-b01f-234630154e96")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IThumbnailProvider
    {
        void GetThumbnail(uint squareLength, out IntPtr hBitmap, out UInt32 bitmapType);
    }

    [ComVisible(true)]
    [Guid("b824b49d-22ac-4161-ac8a-9916e8fa3f7f")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IInitializeWithStream
    {
        void Initialize(IStream stream, UInt32 grfMode);
    }
	
	[ComVisible(true)]
	[Guid("b7d14566-0509-4cce-a71f-0a554233bd9b")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IInitializeWithFile
	{
		void Initialize([MarshalAs(UnmanagedType.LPWStr)]string pszFilePath, UInt32 grfMode);
	}

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("Hiperscan.ThumbnailProvider")]
    [Guid("12ad2950-7e17-11df-8c4a-0800200c9a66")]
    public class ThumbnailProvider : IThumbnailProvider, IInitializeWithStream
    {
		private byte[] buffer;

		
        public void GetThumbnail(uint size, out IntPtr hbitmap, out uint bitmap_type)
        {
            hbitmap = IntPtr.Zero;
            bitmap_type = 0;

            try
            {
				Spectrum[] spectra = new Spectrum[0];
				Color color = Color.AntiqueWhite;

				CSV._IgnoreCorrection = true;
				try
				{
					using (MemoryStream mstream = new MemoryStream(this.buffer))
					{
						spectra = new Spectrum[] { CSV.Read(mstream) };
					}
				}
				catch
				{
					using (MemoryStream mstream = new MemoryStream(this.buffer))
					{
						spectra = CSV.ReadContainer(mstream);
						color = Color.LightGreen;
					}
				}

				Bitmap bmp = Thumbnailer.CreateThumbnailBitmap(spectra, color, (int)size, (int)size);
                hbitmap = bmp.GetHbitmap();
            }
            catch //(Exception ex)
			{
//				using (Stream s = File.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Error.txt"), FileMode.OpenOrCreate))
//                {
//                    using (StreamWriter w = new StreamWriter(s))
//						w.WriteLine(ex.ToString());
//				}
			}
        }
		
        public void Initialize(IStream stream, uint grfMode)
        {
			STATSTG stat;
			stream.Stat(out stat, 1);
			
			this.buffer = new byte[stat.cbSize];
			IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(UInt64)));
			try
			{
				stream.Read(this.buffer, this.buffer.Length, p);
				Marshal.FinalReleaseComObject(stream);
			}
			finally
			{
				Marshal.FreeCoTaskMem(p);
			}
        }

//        protected PlotSurface2D CreatePlotsurface()
//        {
//            Debug.Assert(this.stream != null);
//
//            STATSTG stat;
//            stream.Stat(out stat, 1);
//
//            byte[] data = new byte[stat.cbSize];
//            IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(UInt64)));
//            this.stream.Read(data, data.Length, p);
//            Marshal.FreeCoTaskMem(p);
//
//            Spectrum spectrum;
//            using (MemoryStream memstream = new MemoryStream(data))
//            {
//                spectrum = CSV.Read(memstream);
//            }
//			
////			using (Stream s = File.Open("c:\\users\\klose\\Desktop\\Debug.txt", FileMode.OpenOrCreate))
////			{
////				using (StreamWriter w = new StreamWriter(s))
////					w.WriteLine(this.path);
////			}
////
////			Debug.Assert(!string.IsNullOrEmpty(this.path));
////
////			Spectrum spectrum = CSV.Read(this.path);
//			
//            DataSet ds;
//            this.absorbance = spectrum.HasAbsorbance;
//            if (spectrum.HasAbsorbance)
//                ds = spectrum.Absorbance;
//            else
//                ds = spectrum.Intensity;
//
//            PlotSurface2D ps = new PlotSurface2D();
//
//            ps.AutoScaleAutoGeneratedAxes = false;
//            ps.AutoScaleTitle = false;
//            ps.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//            ps.PlotBackColor = Color.Transparent;
//
//            LinePlot lp = new LinePlot();
//            lp.AbscissaData = ds.X;
//            lp.OrdinateData = ds.Y;
//            lp.Pen = new Pen(Color.Blue, 2f);
//
//            ps.Add(lp);
//
//            ps.XAxis1.WorldMin = ds.XMin();
//            ps.XAxis1.WorldMax = ds.XMax();
//            ps.YAxis1.WorldMin = ds.YMin();
//            ps.YAxis1.WorldMax = ds.YMax();
//            ps.XAxis1.Hidden = true;
//            ps.YAxis1.Hidden = true;
//
//            return ps;
//        }
    }
}