#Requires -Version 5.1
<#
.SYNOPSIS
    ImajViewer Windows kurulum scripti

.DESCRIPTION
    Flutter build ciktilarini alip Windows sisteme kurar.
    Linux install.sh'nin Windows karsiligidir.

    Islevleri:
      - Binary + DLL'leri hedef dizine kopyalar
      - Registry'de dosya association'larini kaydeder (PNG, JPG, JPEG, WebP, BMP, GIF)
      - Start Menu kisayolu olusturur
      - Masamustu kisayolu olusturur (isteğe bagli)
      - Uninstall girdisi olusturur

.PARAMETER InstallDir
    Kurulum dizini (varsayilan: %ProgramFiles%\ImajViewer)

.PARAMETER AddDesktopIcon
    Masamustu kisayolu olusturur

.PARAMETER RegisterAsDefault
    ImajViewer'yi varsayilan goruntu goruntuleyici yapar

.PARAMETER CurrentUser
    Sadece guncel kullanici icin kur (admin hakki gerekmez, %LOCALAPPDATA% kullanilir)

.EXAMPLE
    .\install.ps1
    .\install.ps1 -InstallDir "C:\Apps\ImajViewer" -AddDesktopIcon
    .\install.ps1 -CurrentUser -RegisterAsDefault
#>

param(
    [string]$InstallDir = "",
    [switch]$AddDesktopIcon,
    [switch]$RegisterAsDefault,
    [switch]$CurrentUser
)

# Renkli cikti
function Write-Step { param([string]$Msg) Write-Host "`n> $Msg" -ForegroundColor Cyan }
function Write-Ok   { param([string]$Msg) Write-Host "  [OK] $Msg" -ForegroundColor Green }
function Write-Err  { param([string]$Msg) Write-Host "  [X]  $Msg" -ForegroundColor Red; exit 1 }
function Write-Warn { param([string]$Msg) Write-Host "  [!]  $Msg" -ForegroundColor Yellow }

$ErrorActionPreference = 'Stop'
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$AppName = "ImajViewer"
$AppExe = "imajviewer.exe"
$AppVersion = "1.1.0"
$UninstallGuid = "B8F4A3D2-1C5E-4A7B-9D0F-6E2C8A1B3D5F"

# ── Kurulum dizini belirleme ─────────────────────────────
if (-not $InstallDir) {
    if ($CurrentUser) {
        $InstallDir = Join-Path $env:LOCALAPPDATA $AppName
    } else {
        $InstallDir = Join-Path ${env:ProgramFiles(x86)} $AppName
        if (-not (Test-Path ${env:ProgramFiles(x86)})) {
            $InstallDir = Join-Path $env:ProgramFiles $AppName
        }
    }
}

# ── Build cikti dizini bul ───────────────────────────────
$buildPaths = @(
    Join-Path $ProjectRoot "build\windows\x64\runner\Release",
    Join-Path $ProjectRoot "build\windows\x64\runner\Debug"
)
$BuildDir = $buildPaths | Where-Object { Test-Path (Join-Path $_ $AppExe) } | Select-Object -First 1

if (-not $BuildDir) {
    Write-Err "Build cikti bulunamadi! Once 'flutter build windows --release' calistirin veya build-windows.ps1 kullanin."
}

Write-Host "=" * 60 -ForegroundColor White
Write-Host "  ImajViewer Windows Kurulum" -ForegroundColor White
Write-Host "=" * 60 -ForegroundColor White
Write-Host "  Build Dir    : $BuildDir" -ForegroundColor Gray
Write-Host "  Install Dir  : $InstallDir" -ForegroundColor Gray
Write-Host "  CurrentUser  : $CurrentUser" -ForegroundColor Gray
Write-Host ""

# ── Admin kontrolu (CurrentUser degilse) ──────────────────
if (-not $CurrentUser) {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Write-Err "Bu kurulum admin hakki gerektiriyor. `n`n    1. PowerShell'i 'Yonetici olarak calistir' modunda acin, veya`n    2. '-CurrentUser' parametresi ile kullanici bazli kurun.`n`n    .\install.ps1 -CurrentUser"
    }
}

# ── Hedef dizin olustur ──────────────────────────────────
Write-Step "Kurulum dizini hazirlaniyor..."
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
Write-Ok "Dizin: $InstallDir"

# ── Dosyalari kopyala ─────────────────────────────────────
Write-Step "Dosyalar kopyalaniyor..."
Copy-Item -Path (Join-Path $BuildDir "*") -Destination $InstallDir -Recurse -Force
Write-Ok "Dosyalar kopyalandi"

# Exe dosyasini kontrol et
$installedExe = Join-Path $InstallDir $AppExe
if (-not (Test-Path $installedExe)) {
    Write-Err "$AppExe kurulum dizininde bulunamadi!"
}

# ── Registry: Uninstall girdisi ──────────────────────────
Write-Step "Uninstall girdisi olusturuluyor..."

if ($CurrentUser) {
    $regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$UninstallGuid"
} else {
    $regPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$UninstallGuid"
}

New-Item -Path $regPath -Force | Out-Null
Set-ItemProperty -Path $regPath -Name "DisplayName"        -Value $AppName
Set-ItemProperty -Path $regPath -Name "DisplayVersion"     -Value $AppVersion
Set-ItemProperty -Path $regPath -Name "Publisher"          -Value "imajviewer"
Set-ItemProperty -Path $regPath -Name "InstallLocation"    -Value $InstallDir
Set-ItemProperty -Path $regPath -Name "UninstallString"    -Value "`"$PSScriptRoot\uninstall.ps1`" --install-dir `"$InstallDir`""
Set-ItemProperty -Path $regPath -Name "DisplayIcon"        -Value "$installedExe,0"
Set-ItemProperty -Path $regPath -Name "EstimatedSize"      -Value (
    (Get-ChildItem -Path $InstallDir -Recurse | Measure-Object -Property Length -Sum).Sum / 1KB
) -Type DWord
Write-Ok "Registry: $regPath"

# ── Start Menu kisayolu ──────────────────────────────────
Write-Step "Start Menu kisayolu olusturuluyor..."

if ($CurrentUser) {
    $startMenu = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs"
} else {
    $startMenu = [Environment]::GetFolderPath("CommonPrograms")
}

New-Item -ItemType Directory -Force -Path $startMenu | Out-Null
$shortcutPath = Join-Path $startMenu "$AppName.lnk"

$WshShell = New-Object -ComObject WScript.Shell
$shortcut = $WshShell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = $installedExe
$shortcut.WorkingDirectory = $InstallDir
$shortcut.Description = "Ultra hafif goruntu goruntuleyici"
$shortcut.Save()
Write-Ok "Start Menu: $shortcutPath"

# ── Masaustu kisayolu (isteğe bagli) ─────────────────────
if ($AddDesktopIcon) {
    Write-Step "Masaustu kisayolu olusturuluyor..."
    $desktop = [Environment]::GetFolderPath("Desktop")
    $desktopShortcut = Join-Path $desktop "$AppName.lnk"

    $shortcut2 = $WshShell.CreateShortcut($desktopShortcut)
    $shortcut2.TargetPath = $installedExe
    $shortcut2.WorkingDirectory = $InstallDir
    $shortcut2.Description = "Ultra hafif goruntu goruntuleyici"
    $shortcut2.Save()
    Write-Ok "Masaustu: $desktopShortcut"
}

# ── Dosya association'lar ────────────────────────────────
$imageExtensions = @(".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif")
$mimeTypes = @(
    "image/png", "image/jpeg", "image/jpg",
    "image/webp", "image/bmp", "image/gif"
)

Write-Step "Dosya association'lar kaydediliyor..."

# Applications\imajviewer.exe\shell\open\command
$appRegKey = "HKCU:\Software\Classes\Applications\$AppExe\shell\open\command"
New-Item -Path $appRegKey -Force | Out-Null
Set-ItemProperty -Path $appRegKey -Name "" -Value "`"$installedExe`" `"%1`""
Write-Ok "Applications registry girdisi olusturuldu"

# Her dosya uzantisi icin OpenWithProgids
foreach ($ext in $imageExtensions) {
    $extKey = "HKCU:\Software\Classes\$ext\OpenWithProgids"
    if (-not (Test-Path $extKey)) {
        New-Item -Path $extKey -Force | Out-Null
    }
    # ImajViewer progid'sini ekle (bozukluk yaratmamak icin mevcut degeri koru)
    $existing = Get-ItemProperty -Path $extKey -ErrorAction SilentlyContinue
    $progidName = "ImajViewer"
    $existing | Add-Member -MemberType NoteProperty -Name $progidName -Value "" -Force | Out-Null
    Set-ItemProperty -Path $extKey -Name $progidName -Value ""
    Write-Ok "$ext association eklendi"
}

# ── Varsayilan goruntu goruntuleyici (isteğe bagli) ──────
if ($RegisterAsDefault) {
    Write-Step "Varsayilan goruntu goruntuleyici olarak ayarlaniyor..."

    try {
        # Windows 10/11: SetAsAssociationManager veya Set-ItemProperty ile
        foreach ($ext in $imageExtensions) {
            $userChoiceKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\$ext\UserChoice"
            if (Test-Path $userChoiceKey) {
                Set-ItemProperty -Path $userChoiceKey -Name "ProgId" -Value "Applications\$AppExe"
                Write-Ok "$ext varsayilan olarak $AppName ayarlandi"
            }
        }
    } catch {
        Write-Warn "Varsayilan degisitirme basarisiz (kullanici arayuzu uzerinden degerlendirebilirsiniz): $_"
    }
}

# ── Tamamlandı ────────────────────────────────────────────
Write-Host ""
Write-Host ("=" * 60) -ForegroundColor Green
Write-Host "  $AppName kuruldu!" -ForegroundColor Green
Write-Host "" -ForegroundColor Green
Write-Host "  Kurulum dizini : $InstallDir" -ForegroundColor Green
Write-Host "  Gorsel dosyalara sag tik > 'Birlikte ac' > $AppName" -ForegroundColor Green
Write-Host "" -ForegroundColor Green
Write-Host "  Kaldirmak icin  : .\uninstall.ps1" -ForegroundColor Green
Write-Host "                 veya Ayarlar > Uygulamalar > $AppName" -ForegroundColor Green
Write-Host ("=" * 60) -ForegroundColor Green
Write-Host ""
