using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using Point = System.Windows.Point;

namespace InABox.DynamicGrid
{
    public class WpfScreen
    {
        private readonly Screen screen;

        internal WpfScreen(Screen screen)
        {
            this.screen = screen;
        }

        public static WpfScreen Primary => new(Screen.PrimaryScreen);

        public Rect DeviceBounds => GetRect(screen.Bounds);

        public Rect WorkingArea => GetRect(screen.WorkingArea);

        public bool IsPrimary => screen.Primary;

        public string DeviceName => screen.DeviceName;

        public static IEnumerable<WpfScreen> AllScreens()
        {
            foreach (var screen in Screen.AllScreens) yield return new WpfScreen(screen);
        }

        public static WpfScreen GetScreenFrom(Window window)
        {
            var windowInteropHelper = new WindowInteropHelper(window);
            var screen = Screen.FromHandle(windowInteropHelper.Handle);
            var wpfScreen = new WpfScreen(screen);
            return wpfScreen;
        }

        public static WpfScreen GetScreenFrom(Point point)
        {
            var x = (int)Math.Round(point.X);
            var y = (int)Math.Round(point.Y);

            // are x,y device-independent-pixels ??
            var drawingPoint = new System.Drawing.Point(x, y);
            var screen = Screen.FromPoint(drawingPoint);
            var wpfScreen = new WpfScreen(screen);

            return wpfScreen;
        }

        private Rect GetRect(Rectangle value)
        {
            // should x, y, width, height be device-independent-pixels ??
            return new Rect
            {
                X = value.X,
                Y = value.Y,
                Width = value.Width,
                Height = value.Height
            };
        }

        public static void CenterWindowOnScreen(Window window)
        {
            var screen = GetScreenFrom(window);
            var screenWidth = screen.WorkingArea.Width;
            var screenHeight = screen.WorkingArea.Height;
            var windowWidth = window.Width;
            var windowHeight = window.Height;
            window.Left = screenWidth / 2 - windowWidth / 2;
            window.Top = screenHeight / 2 - windowHeight / 2;
        }
    }
}