$script:bg    = [System.ConsoleColor]::Black;
$script:fg    = [System.ConsoleColor]::White;
$script:first = $true;
$script:last  = 0;

function Get-If {
    [CmdletBinding()]param(
        $Condition,
        $IfTrue,
        $IfFalse
    )

    if ($Condition) {
        $IfTrue
    } else {
        $IfFalse 
    }
}

New-Alias ?: Get-If

function Write-PromptFancyEnd {
    Write-Host  -NoNewline -ForegroundColor $script:fg

    $script:bg = [System.ConsoleColor]::Black
    $script:fg = [System.ConsoleColor]::White
}

if ($IsWindows) { 
    $script:separator = '\';
} else {
    $script:separator = '/';
}

$global:PromptReplacementDirs = @{
    $(?: $IsWindows $env:USERPROFILE $env:HOME) = '~'
}

function Write-PromptSegment {
    param(
        [Parameter(
            Position=0,
            Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true
        )][string]$Text,

        [Parameter(Position=1)][System.ConsoleColor] $Foreground = [System.ConsoleColor]::White,
        [switch] $NoSegment
    )

    Write-Host $text -NoNewline -ForegroundColor $Foreground
    
    if (-not $NoSegment) {
        Write-Host  -NoNewline -ForegroundColor $Foreground
    }

    $script:fg = $Foreground;
}

function Get-FancyDir {
    $location = $(Get-Location).ToString();
    foreach($replacement in $global:PromptReplacementDirs.GetEnumerator()) {
        $location = $location.Replace($replacement.Name, $replacement.Value);
    }

    return $location.Replace($script:separator, '  ');
}

function Get-GitBranch {
    $HEAD = Get-Content $(Join-Path $(Get-GitDirectory) HEAD)
    if($HEAD -like 'ref: refs/heads/*') {
        return $HEAD -replace 'ref: refs/heads/(.*?)', "$1";
    } else {
        return $HEAD.Substring(0, 8);
    }
}

function Write-PromptStatus {
    if($script:last) {
        Write-PromptSegment ' ✔ ' Green
    } else {
        Write-PromptSegment " ✖ $lastexitcode " Red
    }
}

function Write-PromptUser {
    if($global:admin) {
        Write-PromptSegment ' ADMIN ' Red
    }
}

function Write-PromptVirtualEnv {
    if($env:VIRTUAL_ENV) {
        Write-PromptSegment " $(split-path $env:VIRTUAL_ENV -leaf) " Cyan
    }
}

function Write-PromptDir {
    Write-PromptSegment " $(Get-FancyDir) " Gray -NoSegment
}

# Depends on posh-git
function Write-PromptGit {
#    if(Get-GitDirectory) {
#        Write-PromptSegment "  $(Get-GitBranch) " Blue
#    }
}

function prompt {
    $script:last  = $?;
    $script:first = $true;

    Write-PromptStatus
    Write-PromptUser
    Write-PromptVirtualEnv
    Write-PromptGit    
    Write-PromptDir

    Write-PromptFancyEnd

    return ' '
}
