param(
  [switch]$ApagarDados,
  [switch]$PreservarDados,
  [switch]$ConfirmadoPeloSetup
)

$ErrorActionPreference = "Stop"
$scriptPath = $MyInvocation.MyCommand.Path

if ($ApagarDados -and $PreservarDados) {
  throw "Escolha apenas uma opcao: apagar ou preservar os dados."
}

# A remocao da regra de rede e do registro HTTP exige Administrador.
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
$isAdministrator = $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdministrator) {
  $powerShellPath = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
  $arguments = "-NoProfile -ExecutionPolicy Bypass -Sta -File `"$scriptPath`""
  if ($ApagarDados) { $arguments += " -ApagarDados" }
  if ($PreservarDados) { $arguments += " -PreservarDados" }
  if ($ConfirmadoPeloSetup) { $arguments += " -ConfirmadoPeloSetup" }
  Start-Process -FilePath $powerShellPath -ArgumentList $arguments -Verb RunAs | Out-Null
  exit 0
}

Add-Type -AssemblyName System.Windows.Forms

$installRoot = Join-Path $env:LOCALAPPDATA "AmbrosiaNativo"
$installedLauncher = Join-Path $installRoot "iniciar-nativo.ps1"
$installedScriptsRoot = Join-Path $installRoot "scripts"
$installedUninstallBatch = Join-Path $installRoot "DESINSTALAR-Ambrosia-Nativo.bat"
$desktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "Ambrosia Nativo.lnk"
$menuFolder = Join-Path ([Environment]::GetFolderPath("Programs")) "Ambrosia"
$menuShortcut = Join-Path $menuFolder "Ambrosia Nativo.lnk"
$menuUninstallShortcut = Join-Path $menuFolder "Desinstalar Ambrosia Nativo.lnk"
$uninstallKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\AmbrosiaNativo"
$acceptanceKey = "HKCU:\Software\Nativo Sistemas\Ambrosia Nativo"

$deleteData = [bool]$ApagarDados
if (-not $ConfirmadoPeloSetup -and -not $ApagarDados -and -not $PreservarDados) {
  $message = "Deseja apagar tambem os dados do restaurante?`r`n`r`n" +
    "SIM: remove programa, mesas, pedidos, usuarios, configuracoes e backups.`r`n" +
    "NAO: remove somente o programa e preserva todos os dados (recomendado).`r`n" +
    "CANCELAR: nao faz nenhuma alteracao."
  $choice = [System.Windows.Forms.MessageBox]::Show(
    $message,
    "Desinstalar Ambrosia Nativo",
    [System.Windows.Forms.MessageBoxButtons]::YesNoCancel,
    [System.Windows.Forms.MessageBoxIcon]::Question,
    [System.Windows.Forms.MessageBoxDefaultButton]::Button2
  )
  if ($choice -eq [System.Windows.Forms.DialogResult]::Cancel) { exit 0 }
  $deleteData = $choice -eq [System.Windows.Forms.DialogResult]::Yes
}

if ($deleteData -and -not $ConfirmadoPeloSetup) {
  $confirmation = [System.Windows.Forms.MessageBox]::Show(
    "ATENCAO: todos os dados locais e backups do Ambrosia serao apagados definitivamente.`r`n`r`nDeseja continuar?",
    "Confirmar exclusao dos dados",
    [System.Windows.Forms.MessageBoxButtons]::YesNo,
    [System.Windows.Forms.MessageBoxIcon]::Warning,
    [System.Windows.Forms.MessageBoxDefaultButton]::Button2
  )
  if ($confirmation -ne [System.Windows.Forms.DialogResult]::Yes) { exit 0 }
}

Write-Host ""
Write-Host "DESINSTALADOR AMBROSIA NATIVO - V2.8.4" -ForegroundColor DarkYellow
Write-Host "Fechando o aplicativo..." -ForegroundColor Gray

Get-Process -ErrorAction SilentlyContinue |
  Where-Object { $_.ProcessName -like "AmbrosiaNativo*" } |
  Stop-Process -Force -ErrorAction SilentlyContinue

$installedLauncherPattern = "*" + $installedLauncher.Replace("\", "*") + "*"
Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
  Where-Object {
    ($_.Name -eq "powershell.exe" -or $_.Name -eq "pwsh.exe") -and
    $_.CommandLine -like $installedLauncherPattern -and
    $_.ProcessId -ne $PID
  } |
  ForEach-Object { Invoke-CimMethod -InputObject $_ -MethodName Terminate -ErrorAction SilentlyContinue | Out-Null }
Start-Sleep -Milliseconds 700

Write-Host "Removendo os atalhos e o acesso de rede local..." -ForegroundColor Gray
Remove-Item -LiteralPath $desktopShortcut -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $menuShortcut -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $menuUninstallShortcut -Force -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath $menuFolder -PathType Container) {
  $remainingMenuItems = Get-ChildItem -LiteralPath $menuFolder -Force -ErrorAction SilentlyContinue
  if ($null -eq $remainingMenuItems) { Remove-Item -LiteralPath $menuFolder -Force -ErrorAction SilentlyContinue }
}

& netsh http delete urlacl url=http://+:8787/ 2>$null | Out-Null
& netsh advfirewall firewall delete rule name="Ambrosia Atendimento Mobile" 2>$null | Out-Null
Remove-Item -LiteralPath $uninstallKey -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $acceptanceKey -Recurse -Force -ErrorAction SilentlyContinue

if (-not (Test-Path -LiteralPath $installRoot -PathType Container)) {
  [System.Windows.Forms.MessageBox]::Show(
    "O Ambrosia Nativo ja foi removido deste computador.",
    "Ambrosia Nativo",
    [System.Windows.Forms.MessageBoxButtons]::OK,
    [System.Windows.Forms.MessageBoxIcon]::Information
  ) | Out-Null
  exit 0
}

if ($deleteData) {
  $resultMessage = "Programa e todos os dados locais foram removidos."
}
else {
  Get-ChildItem -LiteralPath $installRoot -Filter "AmbrosiaNativo*.exe" -File -ErrorAction SilentlyContinue |
    Remove-Item -Force -ErrorAction SilentlyContinue
  foreach ($fileName in @(
    "AmbrosiaNativo.cs",
    "iniciar-nativo.ps1",
    "NativoSistemas.ico",
    "NativoSistemas.png",
    "SetupBanner.png",
    "TERMOS-DE-USO.txt",
    "erro-inicializacao.txt"
  )) {
    Remove-Item -LiteralPath (Join-Path $installRoot $fileName) -Force -ErrorAction SilentlyContinue
  }
  $resultMessage = "Programa removido. Seus dados e backups foram preservados em:`r`n$installRoot"
}

# Um limpador temporario exclui o desinstalador depois que ele termina.
$cleanupFile = Join-Path $env:TEMP ("AmbrosiaNativo-limpeza-" + [Guid]::NewGuid().ToString("N") + ".cmd")
$cleanupLines = @("@echo off", "ping 127.0.0.1 -n 3 >nul")
if ($deleteData) {
  $cleanupLines += "rmdir /s /q `"$installRoot`""
}
else {
  $cleanupLines += "rmdir /s /q `"$installedScriptsRoot`""
  $cleanupLines += "del /f /q `"$installedUninstallBatch`""
  $cleanupLines += "del /f /q `"$(Join-Path $installRoot 'AMBROSIA-SETUP.bat')`""
}
$cleanupLines += "del /f /q `"%~f0`""
Set-Content -LiteralPath $cleanupFile -Value $cleanupLines -Encoding ASCII

[System.Windows.Forms.MessageBox]::Show(
  $resultMessage,
  "Desinstalacao concluida",
  [System.Windows.Forms.MessageBoxButtons]::OK,
  [System.Windows.Forms.MessageBoxIcon]::Information
) | Out-Null

Start-Process -FilePath $cleanupFile -WindowStyle Hidden | Out-Null
