#先读我!
#$HdiffFilePath 为 升级包 完整路径
#$GamePath 为 游戏完整路径(非启动器路径)
#$ToolPath 为 hpatchz.exe 完整路径(如果有官方启动器就填写启动器完整路径,如果没有去该地址下载:https://github.com/sisong/HDiffPatch/releases)
param($HdiffFilePath="H:\GameSetup\setup\Genshine Impact\game_2.8.52_2.8.53_hdiff_tODgBJm8uenIGUX5.zip",$GamePath="H:\Games\Genshin Impact\Genshin Impact game")

$ToolPath = 'G:\ProgramFiles\hdiffpatch_v4.1.3'

$github = "https://gist.github.com/LiuQixuan/1a3810046c1152808fc9d65c699f8d8d"
$host.ui.RawUI.WindowTitle = "Install game_hdiff.zip for GenshinImpact"
Write-Host '该文件执行后不可逆,确保升级包与已安装游戏版本适配.'
Write-Host "遇到错误前往项目地址反馈:$github"

$hpatchz = Join-Path $ToolPath -ChildPath 'hpatchz.exe'
if(!(Test-Path $hpatchz)){
    Write-Host "patch工具未找到,复制链接下载解压并更新脚本顶部$ToolPath变量`n下载地址:https://github.com/sisong/HDiffPatch/releases"
    exit
}

function Protect-Exit([string]$keyValue='.',[string]$addtext=''){
    if($addtext -ne ''){
        $addtext = "`t" + $addtext
    }
    $keyText = ''
    if($keyValue -eq '.'){
        $keyText = "任意键"
    }else{
        $keyText = $keyValue
    }
    $isContinue = Read-Host "按$keyText`退出$addtext"
    if($isContinue -match "[$keyValue]" ){
        exit
    }
}

Class Logger{
    $time = ""
    $logPath = ""

    Logger(){
        $this.time = Get-Date -UFormat "%Y_%m_%d_%H_%M"
        $this.logPath = Join-Path -Path $PSScriptRoot -ChildPath "diffInstall.$($this.time).time.log"
    }

    Logger([string]$Path){
        $this.time = Get-Date -UFormat "%Y_%m_%d_%H_%M"
        $this.logPath = Join-Path -Path (Get-ItemProperty -Path $Path).Root -ChildPath "diffInstall.$($this.time).log"
    }

    [void]refreshTime(){
        $this.time = Get-Date -UFormat "%Y_%m_%d_%H_%M_%S"
    }

    [void]print([string]$Message,[string]$type){
        Write-Host -Object "[$($this.time)]-[$($type.ToUpper())]-$Message"
    }

    [void]print([string]$Message){
        $this.print($Message,'Error')
    }

    [void]log([string]$Message,[string]$type){
        Write-Host -Object "[$($this.time)]-[$($type.ToUpper())]-$Message">>$($this.logPath)
    }

    [void]log([string]$Message){
        $this.log($Message,'Error')
    }

    [void]write([string]$Message,[string]$type){
        "[$($this.time)]-[$($type.ToUpper())]-$Message">>$($this.logPath)
    }

    [void]write([string]$Message){
        $this.write($Message,'Error')
    }
}

[Logger]$logger = [Logger]::new()

Protect-Exit -keyValue 'N' -addtext '按其他按键继续'

if((Test-Path -Path $HdiffFilePath) -and ((Get-ItemProperty -Path $HdiffFilePath).Extension -eq '.zip')){
    $tmpPath = Join-Path -Path $GamePath -ChildPath "hdiff"
    if( (Test-Path $GamePath) -and (Get-ChildItem $GamePath).name.Contains('GenshinImpact_Data') ){
        New-Item -ItemType Directory $tmpPath
        Expand-Archive -LiteralPath $HdiffFilePath -DestinationPath $tmpPath
        if(Test-Path -Path (Join-Path -Path $tmpPath -ChildPath 'deletefiles.txt')){
            if(Test-Path -Path (Join-Path -Path $tmpPath -ChildPath 'hdifffiles.txt')){
                $delList = Get-Content (Join-Path -Path $tmpPath -ChildPath 'deletefiles.txt')
            
                foreach($item in $delList){
                    if(!(Remove-Item -Path (Join-Path -Path $GamePath -ChildPath $item))){
                       $logger.write("[FileNotFound]:$item")
                    }
                }
                Remove-Item -Path (Join-Path -Path $tmpPath -ChildPath 'deletefiles.txt')
                foreach($item in Get-Content -Path (Join-Path -Path $tmpPath -ChildPath 'hdifffiles.txt')|ConvertFrom-Json){
                    $oldFilePath = Join-Path -Path $GamePath -ChildPath $item.remoteName
                    $diffFilePath = (Join-Path -Path $tmpPath  -ChildPath $item.remoteName)+'.hdiff'
                    if((Test-Path -Path $oldFilePath) -and (Test-Path -Path $diffFilePath)){
                        &$hpatchz -f $oldFilePath $diffFilePath  $oldFilePath
                    }else{
                       $logger.write("[OldPCKFileNotFound]:$($item.remoteName)")
                    }
                }
                Remove-Item -Path (Join-Path -Path $tmpPath -ChildPath 'hdifffiles.txt')
                Remove-Item -Path (Join-Path -Path $tmpPath -ChildPath 'GenshinImpact_Data\StreamingAssets\Audio\GeneratedSoundBanks') -Force -Recurse
                (Get-ChildItem -Path $tmpPath).FullName|Copy-Item -Recurse -Force -Destination $GamePath
            }else{
                $logger.log("[UpdatePackageBroken]-[FileNotFound:hdifffiles.txt]:$HdiffFilePath")
            }
        }else{
            $logger.log("[UpdatePackageBroken]-[FileNotFound:deletefiles.txt]:$HdiffFilePath")
        }
        Remove-Item -Path $tmpPath -Force -Recurse
        Write-Host "升级完成,现在可以关闭窗口.`n如有错误请把$($logger.logPath)`的内容发到项目留言中寻求帮助.`n项目地址:$github"
        Protect-Exit -keyValue '.'
    }else{
        $logger.log("[PathError]:游戏路径错误,检查路径内是否包含`"GenshinImpact_Data`"文件夹.")
    }
}else{
    $logger.log("[PathError]:升级包路径错误.")
}