[CmdletBinding()]
param(
    [switch]$RemoveData
)

$ErrorActionPreference = "Stop"
$InstallDir = Join-Path $env:LOCALAPPDATA "Programs\JVR Time Tracker"
$StartMenuDir = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\JVR Time Tracker"
$DesktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "JVR Time Tracker.lnk"
$StartupShortcut = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Startup\JVR Time Tracker.lnk"

function Remove-CurrentUserRegistryTree([string]$ProviderPath) {
    $subKey = $ProviderPath.Substring("HKCU:\".Length)
    [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($subKey, $false)
}

$keys = @(
    "HKCU:\Software\Classes\DesktopBackground\Shell\JVRTimeTracker",
    "HKCU:\Software\Classes\Directory\Background\shell\JVRTimeTracker",
    "HKCU:\Software\Classes\Directory\shell\JVRTimeTracker",
    "HKCU:\Software\Classes\*\shell\JVRTimeTracker",
    "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\JVRTimeTracker.Open",
    "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\JVRTimeTracker.Start",
    "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\JVRTimeTracker.Stop",
    "HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths\JVRTimeTracker.exe"
)
foreach ($key in $keys) {
    Remove-CurrentUserRegistryTree $key
}

foreach ($path in @($DesktopShortcut, $StartupShortcut, $StartMenuDir, $InstallDir)) {
    if (Test-Path -LiteralPath $path) {
        Remove-Item -LiteralPath $path -Recurse -Force
    }
}

if ($RemoveData) {
    $dataDir = Join-Path $env:LOCALAPPDATA "JVR Software\JVR Time Tracker"
    if (Test-Path -LiteralPath $dataDir) {
        $confirmation = Read-Host "Type DELETE MY TIME DATA to permanently remove $dataDir"
        if ($confirmation -eq "DELETE MY TIME DATA") {
            Remove-Item -LiteralPath $dataDir -Recurse -Force
            Write-Host "Time data removed."
        } else {
            Write-Host "Time data preserved because the confirmation did not match."
        }
    }
}

Write-Host "JVR Time Tracker Windows integration removed."
Write-Host "Time data was preserved unless -RemoveData was supplied and explicitly confirmed."
