using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Skyscraper.IO;
using skyscraper8.Skyscraper.Drawing;

namespace skyscraper8.AnagramViewer.Handlers
{
	internal class IQHandler : IFileTypeHandler
	{
		public DataType CheckDataType(Stream input)
		{
			byte readUInt8 = input.ReadUInt8();
			if (readUInt8 == 0x41)
				return DataType.Image;
			return DataType.Unknown;
		}

		public Image AsImage(Stream input)
		{
			IqChartData iqChartData = IqChartData.LoadFrom(input);
			iqChartData.AutoScale();

			Bitmap bitmap = new Bitmap(256, 256,PixelFormat.Format24bppRgb);
			BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

			byte[] buffer = new byte[(256 * 256) * 3];
			int oPos = 0;
			for (int y = 0; y < 256; y++)
			{
				for (int x = 0; x < 256; x++)
				{
					byte b = iqChartData.IQ[y][x];
					if (b != 0)
					{
						buffer[oPos] = b; //R
						buffer[oPos + 1] = 0; //G
						buffer[oPos + 2] = (byte)(255 - b); //B

						buffer[oPos] = (byte)(~buffer[oPos]);
						buffer[oPos + 1] = 0;
						buffer[oPos + 2] = (byte)(~buffer[oPos + 2]);
					}
					else
					{
						buffer[oPos] = 255;
						buffer[oPos + 1] = 255;
						buffer[oPos + 2] = 255;
					}

					oPos += 3;
				}
			}
			
			Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
			bitmap.UnlockBits(bitmapData);
			return bitmap;
		}

		public string AsText(Stream input)
		{
			throw new NotImplementedException();
		}
	}
}
