using System;
using System.Collections.Generic;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;
using Quik.Media;
using Quik.OpenGL;
using Quik.PAL;

namespace Quik.OpenTK
{
    public class OpenTKPlatform : IQuikPlatform
    {
        private readonly List<OpenTKPort> _ports = new List<OpenTKPort>();

        // These shall remain a sad nop for now.
        public string Title { get; set; }
        public QImage Icon { get; set; }

        public event EventHandler EventRaised;

        public NativeWindowSettings DefaultSettings { get; set; } = NativeWindowSettings.Default;

        public IReadOnlyList<OpenTKPort> Ports => _ports;

        private bool IsGLInitialized = false;

        public IQuikPort CreatePort()
        {
            NativeWindow window = new NativeWindow(DefaultSettings);
            OpenTKPort port = new OpenTKPort(window);
            _ports.Add(port);

            if (!IsGLInitialized)
            {
                window.Context.MakeCurrent();
                GL.LoadBindings((string proc) => GLFW.GetProcAddress(proc));
                IsGLInitialized = true;
            }

            return port;
        }

        public void Dispose()
        {
            // FIXME: dispose pattern here!

            // Copy the array to prevent collection modification exceptions.
            foreach (OpenTKPort port in _ports.ToArray())
            {
                port.Dispose();
            }
        }

        public void ProcessEvents(bool block)
        {
            NativeWindow.ProcessWindowEvents(block);
        }
    }
}