using System;
using System.Text;
using System.Threading.Tasks;
using Bridge.Html5;
using Mox.Shared;
using Mox.Shared.Renderer;
using Mox.Shared.Math;

namespace Mox.Bridge.Renderer
{
	internal class WebGLRenderer : Shared.Renderer.RendererBase
	{
		public WebGLRenderer(HTMLCanvasElement _canvas)
		{
			m_Canvas = _canvas;
			m_Context = _canvas.GetContext("2d").As<CanvasRenderingContext2D>();
			m_Context.ImageSmoothingEnabled = true;

			Instance = this;
		}

		public override async Task<ImageBase> CreateImage(string _sPath)
		{
			return new WebGLImage(await IOHelper.GetBytes(_sPath), _sPath.Substring(_sPath.LastIndexOf('.') + 1));
		}

		public override void FillRect(Rect _rect, Color _color)
		{
			m_Context.FillStyle = $"rgba({(int) (_color.R * 255)}, {(int) (_color.G * 255)}, {(int) (_color.B * 255)}, {_color.A})";
			m_Context.FillRect(_rect.Left, _rect.Top, _rect.Width, _rect.Height);
		}

		public override void DrawImage(ImageBase _image, Rect _source, Rect _target)
		{
			var webGLImage = (WebGLImage) _image;

			m_Context.DrawImage(webGLImage.Image, _source.Left, _source.Top, _source.Width, _source.Height, _target.Left, _target.Top, _target.Width, _target.Height);
		}

		public override void BeginDraw()
		{
		}

		public override void EndDraw()
		{
		}

		public override void Clear(Color _color)
		{
			m_Context.FillStyle = $"rgba({(int) (_color.R * 255)}, {(int) (_color.G * 255)}, {(int) (_color.B * 255)}, {_color.A})";
			m_Context.FillRect(0, 0, m_Canvas.Width, m_Canvas.Height);
		}

		public override void SetTextColor(Color _color)
		{
			m_Context.FillStyle = $"rgba({(int) (_color.R * 255)}, {(int) (_color.G * 255)}, {(int) (_color.B * 255)}, {_color.A})";
		}

		public override void SetTextStyle(string _sFont, int _iSize)
		{
			m_Context.Font = $"normal {_iSize}pt {_sFont}";
		}

		public override void DrawText(string _sText, int _iX, int _iY)
		{
			m_Context.TextBaseline = CanvasTypes.CanvasTextBaselineAlign.Middle;
			m_Context.TextAlign = CanvasTypes.CanvasTextAlign.Center;
			m_Context.FillText(_sText, _iX, _iY);
		}

		public override Rect MeasureText(string _sText)
		{
			var measure = m_Context.MeasureText(_sText);
			return new Rect(0, 0, (int) measure.Width, (int) (measure.EmHeightAscent + measure.EmHeightDescent));
		}

		public override void Dispose()
		{
		}

		private readonly CanvasRenderingContext2D m_Context;
		private readonly HTMLCanvasElement m_Canvas;
	}
}
