# Because we are compatible with PowerShell 5, standard backtick-escaping doesn't work here.
# Therefore, escape sequences are often cast using [char] or a static method thereof.

$Esc = [char]27 # `e

$OriginalPrompt = $(Get-Command Prompt 2>$null).ScriptBlock

gk showWelcomeMessage

function Prompt {
  $cwd = Get-Location
  if ($env:GK_TAB_TYPE -eq "CLI" -or $env:GK_TAB_TYPE -eq "REPO") {
    Start-Process -windowStyle "hidden" -FilePath "powershell.exe" -ArgumentList "gk setCwd '$cwd'"
  }

  $p = "$(Invoke-Command -ScriptBlock $OriginalPrompt)";

  $pLines = $p.split("`n");
  $LastLength = $pLines[$pLines.length-1].length;
  $RowOffset = $pLines.length-1;
  $LengthMarker = "$($Esc)[1314;$($LastLength);$($RowOffset)~"
  $pLines[$pLines.length-1] += $LengthMarker;

  return $pLines -join "`n";
}

# TODO: It would be nice to restore the original prompt on unload, but I haven't found a way to do so.
#       Surely the sorcery can be done by attaching a code block to
#         $MyInvocation.MyCommand.ScriptBlock.Module.OnRemove ...but we don't know exactly what the magic spell is.

Export-ModuleMember -function prompt
