# <copyright file="Watch-PbixFile.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

    A helper for running the Power BI Tools extract command in 'watch' mode.
    Looks up the Power BI Desktop process ID information before running the required 'pbi-tools.exe' command.
    PS C:\> Watch-PbixFile -PbixFilePath myReport.pbix -ExtractPath src/myReport
    When run in the root of a git repository, generates the required pr-autoflow artefacts under the '.github' folder.
    Path to the source PBIX file being edited in Power BI Desktop.
.PARAMETER ExtractPath
    Path to the folder where the PBIX file will be extracted to.
.PARAMETER PbiDesktopPid
    Allows the the Power BI Desktop process ID to be set manually.
    Path to the Power BI Tools Windows CLI tool (i.e 'pbi-tools.exe'). When not specified it is assumed to be in your PATH.

function Watch-PbixFile {
    param (
        [string] $PbixFilePath,

        [string] $ExtractPath,

        [int] $PbiDesktopPid,

        [string] $PbiToolsPath = "pbi-tools.exe"

    if (!$IsWindows) {
        Write-Error "The PBI Tools 'extract' functionality is only supported on Windows."

    try {
        $resolvePbixFilePath = Resolve-Path $PbixFilePath
    catch {
        Write-Error "PBIX file not found: $resolvePbixFilePath"

    if (!(Get-Command $PbiToolsPath)) {
        Write-Error "The PBI Tools CLI could be found as an executable command: $PbiToolsPath"

    if (!$PbiDesktopPid) {
        Write-Host "Looking-up process ID for Power BI Desktop session..." -f Yellow
        $pbiInfo = & $PbiToolsPath info | ConvertFrom-Json -Depth 10
        $PbiDesktopPid = $pbiInfo.pbiSessions |
                            ? { $_.PbixPath -eq $resolvePbixFilePath } |
                            Select-Object -ExpandProperty ProcessId

    if (!$PbiDesktopPid) {
        Write-Error "Unable to find an active Power BI Desktop session for the report: $resolvePbixFilePath"

    & $PbiToolsPath extract $resolvePbixFilePath -extractFolder $ExtractPath -pid $PbiDesktopPid -watch