using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Echo.Core.Common.Packed;
using Echo.UserInterface.Backend;
using ImGuiNET;
using SDL2;
using skyscraper8.Skyscraper.Drawing;
using testdrid.SdlWrapper;

namespace SDL2Demo.Forms
{
    internal class IqWindow : IRenderable, IDisposable
    {
        private readonly Renderer _renderer;
        private readonly Texture _texture;
        private readonly bool imgui;
        private readonly Vector2 _imguiVector;
        private readonly IqChartData _iqPlot;
        
        public IqWindow(Renderer renderer, IqChartData iqPlot)
        {
            _renderer = renderer;
            _texture = Texture.Create(_renderer, SDL.SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, 256, 256);
            _texture.SetDrawBlendMode(SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND);
            _iqPlot = iqPlot;
            imgui = false;
        }

        public IqWindow(ImGuiDevice imGuiDevice, IqChartData iqPlot)
        {
            IntPtr textureIntPtr = imGuiDevice.CreateTexture(new Int2(256, 256), true, !BitConverter.IsLittleEndian);
            _texture = Texture.FromIntPointer(textureIntPtr);
            _renderer = null;
            _imguiVector = new Vector2(256, 256);
            _iqPlot = iqPlot;
			imgui = true;
        }
        

        public Point RenderOffset { get; set; }

        private void RenderInternal()
        {
	        byte b = 0;
	        byte[][] iq = _iqPlot.IQ;
	        for (int y = 0; y < 256; y++)
	        {

				for (int x = 0; x < 256; x++)
		        {

					b = iq[x][y];
                    if (b != 0)
	                    _texture.SetPixel(x, y, 255, (byte)(255 - b), 0, 0);
                    else
	                    _texture.SetPixel(x, y, 0, 0, 0, 0);
				}
	        }
        }

        public void Render()
        {
	        lock (_iqPlot)
	        {
		        _texture.Lock();
		        RenderInternal();
		        _texture.Unlock();

		        if (imgui)
		        {
			        ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, new Vector2(272, 256));
			        ImGui.Begin("IQ", ImGuiWindowFlags.NoResize);
			        ImGui.ProgressBar(_iqPlot.ProgressFraction, Vector2.Zero, String.Format("{0}% (Z={1})", _iqPlot.ProgressHumanReadable, _iqPlot.ZAxis));
			        ImGui.Image(_texture.Pointer, _imguiVector);
			        ImGui.End();
			        ImGui.PopStyleVar();
		        }
		        else
		        {
			        _renderer.Copy(_texture, RenderOffset);
		        }
			}
        }

        private bool disposing;
        public void Dispose()
        {
	        lock (_iqPlot)
	        {
		        disposing = true;
	        }

	        _texture.Dispose();
        }
    }
}
