﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace Oni.Imaging
{
	internal static class SysReader
	{
		public static Surface Read(string filePath)
		{
			using (Bitmap bmp = new Bitmap(filePath, false))
			{
				SurfaceFormat surfaceFormat;
				PixelFormat pixelFormat;

				if (bmp.RawFormat == ImageFormat.Jpeg || bmp.RawFormat == ImageFormat.Bmp)
				{
					surfaceFormat = SurfaceFormat.BGRX;
					pixelFormat = PixelFormat.Format32bppRgb;
				}
				else
				{
					surfaceFormat = SurfaceFormat.BGRA;
					pixelFormat = PixelFormat.Format32bppArgb;
				}

				var surface = new Surface(bmp.Width, bmp.Height, surfaceFormat);
                var rc = new Rectangle(0, 0, bmp.Width, bmp.Height);
                
                var data = bmp.LockBits(rc, ImageLockMode.ReadOnly, pixelFormat);
				Marshal.Copy(data.Scan0, surface.Data, 0, surface.Data.Length);
				bmp.UnlockBits(data);

                return surface;
			}
		}
	}
}
