param(
    [int]$Width = 1920,
    [int]$Height = 1080,
    [string]$Description = 'USB Mobile Monitor Virtual Display',
    [switch]$Primary
)

$ErrorActionPreference = 'Stop'

Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

public static class DisplayMode {
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct DISPLAY_DEVICE {
        public int cb;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DeviceName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceString;
        public int StateFlags;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceID;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceKey;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct DEVMODE {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName;
        public short dmSpecVersion;
        public short dmDriverVersion;
        public short dmSize;
        public short dmDriverExtra;
        public int dmFields;
        public int dmPositionX;
        public int dmPositionY;
        public int dmDisplayOrientation;
        public int dmDisplayFixedOutput;
        public short dmColor;
        public short dmDuplex;
        public short dmYResolution;
        public short dmTTOption;
        public short dmCollate;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
        public short dmLogPixels;
        public int dmBitsPerPel;
        public int dmPelsWidth;
        public int dmPelsHeight;
        public int dmDisplayFlags;
        public int dmDisplayFrequency;
        public int dmICMMethod;
        public int dmICMIntent;
        public int dmMediaType;
        public int dmDitherType;
        public int dmReserved1;
        public int dmReserved2;
        public int dmPanningWidth;
        public int dmPanningHeight;
    }

    [DllImport("user32.dll", CharSet = CharSet.Ansi)]
    static extern bool EnumDisplayDevices(string device, uint index, ref DISPLAY_DEVICE display, uint flags);

    [DllImport("user32.dll", CharSet = CharSet.Ansi)]
    static extern bool EnumDisplaySettings(string device, int mode, ref DEVMODE settings);

    [DllImport("user32.dll", CharSet = CharSet.Ansi)]
    static extern int ChangeDisplaySettingsEx(string device, ref DEVMODE settings, IntPtr window, uint flags, IntPtr param);

    public static string SetResolution(string description, bool primary, int width, int height) {
        for (uint index = 0; ; index++) {
            var display = new DISPLAY_DEVICE();
            display.cb = Marshal.SizeOf(display);
            if (!EnumDisplayDevices(null, index, ref display, 0)) break;
            bool isPrimary = (display.StateFlags & 4) != 0;
            if (primary ? !isPrimary : !string.Equals(display.DeviceString, description, StringComparison.OrdinalIgnoreCase)) continue;

            var settings = new DEVMODE();
            settings.dmSize = (short)Marshal.SizeOf(settings);
            if (!EnumDisplaySettings(display.DeviceName, -1, ref settings))
                throw new InvalidOperationException("EnumDisplaySettings failed for " + display.DeviceName);

            settings.dmPelsWidth = width;
            settings.dmPelsHeight = height;
            settings.dmFields = 0x00080000 | 0x00100000;

            int test = ChangeDisplaySettingsEx(display.DeviceName, ref settings, IntPtr.Zero, 0x00000002, IntPtr.Zero);
            if (test != 0) throw new InvalidOperationException("Resolution test failed with code " + test);

            int apply = ChangeDisplaySettingsEx(display.DeviceName, ref settings, IntPtr.Zero, 0x00000001, IntPtr.Zero);
            if (apply != 0) throw new InvalidOperationException("Resolution change failed with code " + apply);
            return display.DeviceName;
        }
        throw new InvalidOperationException("USB Mobile Monitor Virtual Display not found");
    }
}
'@

$device = [DisplayMode]::SetResolution($Description, $Primary.IsPresent, $Width, $Height)
Start-Sleep -Seconds 2

if ($Primary) {
    Add-Type -AssemblyName System.Windows.Forms
    $actualWidth = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width
    $actualHeight = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height
} else {
    $display = Get-CimInstance Win32_VideoController |
        Where-Object Name -eq $Description |
        Select-Object -First 1
    $actualWidth = $display.CurrentHorizontalResolution
    $actualHeight = $display.CurrentVerticalResolution
}

if ($actualWidth -ne $Width -or $actualHeight -ne $Height) {
    throw "Resolution verification failed: $($actualWidth)x$($actualHeight)"
}

Write-Output "$device $Width`x$Height"
