using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SDL2;

namespace testdrid.SdlWrapper
{
    internal class Window : IDisposable
    {
        private Window() {}

        internal IntPtr Pointer { get; set; }

        public static Window Create(string title, int width, int height)
        {
            return Create(title, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, width, height, SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL);
        }

        public static Window Create(string title, int x, int y, int width, int height, SDL.SDL_WindowFlags flags)
        {
            Window window = new Window();
            window._fullscreen = flags.HasFlag(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
            window.Pointer = SDL.SDL_CreateWindow(title, x, y, width, height, flags);
            if (window.Pointer == IntPtr.Zero)
            {
                throw SdlException.GenerateException();
            }
            return window;
        }

        public void Dispose()
        {
            SDL.SDL_DestroyWindow(Pointer);
            Pointer = IntPtr.Zero;
        }

        public void GlSwap()
        {
            SDL.SDL_GL_SwapWindow(Pointer);
        }

        private bool _fullscreen;

        public bool Fullscreen
        {
            get
            {
                return _fullscreen;
            }
            set
            {
                if (SDL.SDL_SetWindowFullscreen(Pointer, value ? (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP : 0) != 0)
                {
                    throw SdlException.GenerateException();
                }
            }
        }

        public Rectangle GetWindowRectangle()
        {
            int w = -1, h = -1, left = -1, top = -1;
            SDL.SDL_GetWindowSize(this.Pointer, out w, out h);
            SDL.SDL_GetWindowPosition(this.Pointer, out left, out top);
            return new Rectangle(left, top, w, h);
        }
    }
}
