
$script:SmPlayerProjectRoot = Split-Path -Parent $PSScriptRoot
$script:SmPlayerVersionCli = Join-Path $PSScriptRoot 'version.dart'

function Get-SmPlayerCurrentVersion {
    param(
        [Parameter(Mandatory = $true)][string]$Platform,
        [string]$ProjectRoot = $script:SmPlayerProjectRoot
    )

    return (& dart $script:SmPlayerVersionCli current $Platform --project-root $ProjectRoot)
}

function ConvertTo-SmPlayerBuildNumber {
    param([Parameter(Mandatory = $true)][string]$Version)

    return [int](& dart $script:SmPlayerVersionCli build-number $Version)
}

function Test-SmPlayerFlutterOptionPresent {
    param(
        [string[]]$Arguments = @(),
        [Parameter(Mandatory = $true)][string]$OptionName
    )

    foreach ($argument in @($Arguments)) {
        if ($argument -eq $OptionName -or $argument.StartsWith("$OptionName=")) { return $true }
    }
    return $false
}

function Test-SmPlayerDartDefinePresent {
    param(
        [string[]]$Arguments = @(),
        [Parameter(Mandatory = $true)][string]$DefineName
    )

    $previousArgument = ''
    foreach ($argument in @($Arguments)) {
        if ($argument -like "--dart-define=$DefineName=*") { return $true }
        if ($previousArgument -eq '--dart-define' -and $argument -like "$DefineName=*") { return $true }
        $previousArgument = $argument
    }
    return $false
}

function Add-SmPlayerVersionDartDefine {
    param(
        [string[]]$Arguments = @(),
        [Parameter(Mandatory = $true)][string]$Version
    )

    $result = @($Arguments)
    if (-not (Test-SmPlayerDartDefinePresent -Arguments $result -DefineName 'SMPLAYER_VERSION')) {
        $result += "--dart-define=SMPLAYER_VERSION=$Version"
    }
    return $result
}

function Add-SmPlayerBuildName {
    param(
        [string[]]$Arguments = @(),
        [Parameter(Mandatory = $true)][string]$Version
    )

    $result = @($Arguments)
    if (-not (Test-SmPlayerFlutterOptionPresent -Arguments $result -OptionName '--build-name')) {
        $result += @('--build-name', $Version)
    }
    return $result
}
