using Photino.NET;
using System.Drawing;
using System.Runtime.InteropServices;

namespace BrikInstaller.Utils;

public static class WindowHelper {

    private const float StandardDpi = 96.0f;
    
    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);

    const int GWL_STYLE = -16;
    const int WS_CAPTION = 0x00C00000;
    const int WS_THICKFRAME = 0x00040000;
    const int WS_MINIMIZEBOX = 0x00020000;
    const int WS_MAXIMIZEBOX = 0x00010000;
    const int WS_SYSMENU = 0x00080000;
    const uint SWP_FRAMECHANGED = 0x0020;
    const uint SWP_NOMOVE = 0x0002;
    const uint SWP_NOSIZE = 0x0001;
    const uint SWP_NOZORDER = 0x0004;
    const uint WM_SETICON = 0x0080;
    const IntPtr ICON_SMALL = 0;
    const IntPtr ICON_BIG = 1;
    const uint IMAGE_ICON = 1;
    const uint LR_LOADFROMFILE = 0x00000010;

    public static Size GetScaledSize(PhotinoWindow window, int logicalWidth, int logicalHeight) {
        float currentDpi = window.ScreenDpi > 0 ? window.ScreenDpi : StandardDpi;
        float scaleFactor = currentDpi / StandardDpi;

        return new Size(
            (int)(logicalWidth * scaleFactor),
            (int)(logicalHeight * scaleFactor)
        );
    }

    public static void setSize(PhotinoWindow window, int width, int height) {
        Size targetSize = GetScaledSize(window, width, height);
        window
            .SetResizable(false)
            .SetSize(targetSize)
            .SetMinSize(targetSize.Width, targetSize.Height);
    }

    public static void RemoveTitleBar(PhotinoWindow window) {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
            IntPtr hWnd = window.WindowHandle;
            int style = GetWindowLong(hWnd, GWL_STYLE);
            style &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU);
            SetWindowLong(hWnd, GWL_STYLE, style);
            SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
        }
    }

    public static void ForceTaskbarIcon(PhotinoWindow window, string iconPath) {
        IntPtr hWnd = window.WindowHandle;
        IntPtr hIcon = LoadImage(IntPtr.Zero, iconPath, IMAGE_ICON, 0, 0, LR_LOADFROMFILE);
        if (hIcon != IntPtr.Zero) {
            SendMessage(hWnd, WM_SETICON, ICON_SMALL, hIcon);
            SendMessage(hWnd, WM_SETICON, ICON_BIG, hIcon);
        }
    }
}