# automatically imports the bindings file into steamvr so you don't have to
# go through the awful UI yourself.
# This uses the undocumented API in the bindings UI itself (it's a webapp).
# SteamVR needs to be running for this to work, but avoids needing to mess with steamvr's json
# config directly.
Write-Host "Checking if SteamVR is running..."
# Check if SteamVR is running
$steamVRProcess = Get-Process -Name "vrcompositor" -ErrorAction SilentlyContinue
if (-not $steamVRProcess) {
    $wshell = New-Object -ComObject Wscript.Shell
    $wshell.Popup("SteamVR is not running. Please start SteamVR and try again.", 0, "SteamVR Not Running", 0x0 + 0x30)
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

Write-Host "Copying bindings file..."
# Get the directory that the script is in
$currentDir = Split-Path -Parent $MyInvocation.MyCommand.Definition

# Source bindings file
$sourceBindingsFile = Join-Path -Path $currentDir -ChildPath "org.jrbudda.vivecraft.steamvrinput_knuckles.json"

# Ensure the source file exists
if (-not (Test-Path $sourceBindingsFile)) {
    Write-Error "Bindings file not found: $sourceBindingsFile"
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

# Construct the path to the SteamVR input import directory
$steamVRImportDir = Join-Path -Path ([Environment]::GetFolderPath("MyDocuments")) -ChildPath "steamvr\input\imports"

# Ensure the SteamVR input import directory exists
if (-not (Test-Path $steamVRImportDir)) {
    New-Item -ItemType Directory -Path $steamVRImportDir -Force
}

# Function to copy and import bindings
function Import-SteamVRBinding {
    param (
        [string]$bindingsFilePath,
        [string]$controllerType
    )

    $fileName = Split-Path $bindingsFilePath -Leaf
    $destBindingsFile = Join-Path -Path $steamVRImportDir -ChildPath $fileName

    # Copy the bindings file
    Copy-Item -Path $bindingsFilePath -Destination $destBindingsFile -Force

    Write-Host "Calling SteamVR API for $controllerType..."
    # Convert the destination file path to a file URI
    $fileUri = [System.Uri]::new($destBindingsFile).AbsoluteUri

    # Construct the body with the correct file URI
    $body = @{
        app_key         = "org.jrbudda.vivecraft.steamvrinput"
        controller_type = $controllerType
        url             = $fileUri
    } | ConvertTo-Json

    try {
        $response = Invoke-WebRequest -UseBasicParsing -Uri "http://localhost:27062/input/selectconfig.action" `
            -Method POST `
            -Headers @{
            "Accept"  = "application/json, text/plain, */*"
            "Origin"  = "http://localhost:27062"
            "Referer" = "http://localhost:27062/dashboard/controllerbinding.html"
        } `
            -ContentType "application/json" `
            -Body $body

        if ($response.StatusCode -eq 200) {
            Write-Host "Successfully set recommended SteamVR bindings for Vivecraft ($controllerType)."
        }
    }
    catch {
        Write-Error "Failed to call the API for $controllerType: $_"
        return $false
    }

    return $true
}

# Get the directory that the script is in
$currentDir = Split-Path -Parent $MyInvocation.MyCommand.Definition

# Define bindings and controller types
$bindings = @(
    @{
        File = "org.jrbudda.vivecraft.steamvrinput_knuckles.json"
        Type = "knuckles"
    },
    @{
        File = "org.jrbudda.vivecraft.steamvrinput_pico_controller.json"
        Type = "pico_controller"
    }
    # Add more bindings here as needed
)

$allSucceeded = $true

foreach ($binding in $bindings) {
    $sourceBindingsFile = Join-Path -Path $currentDir -ChildPath $binding.File

    # Ensure the source file exists
    if (-not (Test-Path $sourceBindingsFile)) {
        Write-Error "Bindings file not found: $sourceBindingsFile"
        $allSucceeded = $false
        continue
    }

    $result = Import-SteamVRBinding -bindingsFilePath $sourceBindingsFile -controllerType $binding.Type
    if (-not $result) {
        $allSucceeded = $false
    }
}

if ($allSucceeded) {
    $wshell = New-Object -ComObject Wscript.Shell
    $wshell.Popup("Successfully set recommended SteamVR bindings for Vivecraft for all controller types.", 0, "Success", 0x0 + 0x40)
} else {
    $wshell = New-Object -ComObject Wscript.Shell
    $wshell.Popup("Some errors occurred while setting SteamVR bindings. Please check the console for details.", 0, "Warning", 0x0 + 0x30)
}

$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")