function Start-PPTSolutionPull {
    [CmdLetBinding()]
    Param (
        [Alias('env')]
        [ValidateSet('DEV', 'STAGING', 'TESTING')]
        [string]$Environment = 'DEV',
        $Path = (Get-Location).Path,
        [Alias('m')]
        [switch]$Managed,
        [Alias('p')]
        [switch]$Patch,
        [Alias('sn')]
        [switch]$SolutionName
    )

    begin {

        $Path = @{
            qualifier    = (Split-Path -Path $Path -Qualifier)
            parent       = (Split-Path -Path $Path)
            leaf         = (Split-Path -Path $Path -Leaf)
            path         = $Path
            pathBuild    = (Join-Path -Path $Path -ChildPath 'Build')
            pathConfig   = (Join-Path -Path $Path -ChildPath 'Build\config.json')
            sourcePath   = (Join-Path -Path $PSScriptRoot -ChildPath 'source')
            sourceConfig = (Join-Path -Path $PSScriptRoot -ChildPath 'source\config.ps1')
            sourceIgnore = (Join-Path -Path $PSScriptRoot -ChildPath 'source\.gitignore')
        }

        $config = (Get-Content $Path.pathConfig | ConvertFrom-Json)
        $env    = ($config.env | ?{$_.name -eq $Environment})

        function ConfiguredEnvironments () {
            if (!$env) {
                do {
                #Write-Host "┌───────────────────────────────────────────────────────────────┐" -ForegroundColor Green
                #Write-Host "│`t`t`t`t`t`t`t`t│ -ForegroundColor Green
                #Write-Host "│" -ForegroundColor Green -NoNewLine; Write-Host "`t`t`tCONFIGURED ENVIRONMENTS`t`t`t" -ForegroundColor Cyan -NoNewline; Write-Host "│" -ForegroundColor Green
                #Write-Host "└───────────────────────────────────────────────────────────────┘" -ForegroundColor Green
                    $config.env | %{"[ {0} ] {1}" -f $_.id,$_.name}
                    $environmentId = Read-Host -Prompt "Select Environment ($((1..$config.env.Count) -join ','))"
                } while ($environmentId -notin (1..$config.env.Count))
                #$env = ($config.env | ?{$_.id -eq $environmentId})
                return ($config.env | ?{$_.id -eq $environmentId})
            }
        }

        function NameThatSolution () {
            #Write-Host "┌───────────────────────────────────────────────────────────────┐" -ForegroundColor Green
            #Write-Host "│" -ForegroundColor Green -NoNewLine; Write-Host "`t`t`tNAME THAT SOLUTION`t`t`t" -ForegroundColor Cyan -NoNewline; Write-Host "│" -ForegroundColor Green
            #Write-Host "└───────────────────────────────────────────────────────────────┘" -ForegroundColor Green
            do {
                $solutionNameProvided = Read-Host -Prompt "Enter Solution Package name"
                If($solutionNameProvided -match '\s*(\W+?)') {
                    Write-Host "We had to fix a few things with the Solution Package name provided [" -NoNewline -ForegroundColor Yellow
                    Write-Host "$($solutionNameProvided)" -NoNewLine -ForegroundColor White
                    Write-Host "]`nHope you're not too upset." -ForegroundColor Yellow
                }
                $solutionNewName = $solutionNameProvided -replace ('\s*(\W+?)', '')
                Write-Host "`n$(If($solutionNameProvided -match '\s*(\W+?)'){"A little fixer upper: "}Else{"Solution Package Name:"})" -NoNewline -ForegroundColor Green
                Write-Host "$($solutionNewName)" -ForegroundColor Magenta
                $continueSolutionName = Read-Host -Prompt "$(If($solutionNameProvided -match '\s*(\W+?)'){"We good?"}Else{"Continue"}) (y/n)"
            } while ($continueSolutionName -ne 'y' -or $continueSolutionName -ne 'Y')
            #$Path.leaf = $solutionNewName
            return $solutionNewName
        }

        function GetAvailablePatches () {
            #Write-Host "┌───────────────────────────────────────────────────────────────┐" -ForegroundColor Green
            #Write-Host "│" -ForegroundColor Green -NoNewLine; Write-Host "`t`t`tAVAILABLE PATCHES`t`t`t" -ForegroundColor Cyan -NoNewline; Write-Host "│" -ForegroundColor Green
            #Write-Host "└───────────────────────────────────────────────────────────────┘" -ForegroundColor Green
            $pacResponse = (& $Global:pptConfig.pacPath solution list | ?{$_ -match $Path.leaf -and $_ -match "patch"}) -split "`r?`n" | %{
                $g1 = ($_ -split "(?'g1'^\S*)")
                $g2 = ($g1[2] -split "((\d+|\.){1,})")[0,1,-1]
                $solutionObject = @{
                    Name = $g1[1]
                    DisplayName = ($g2[0]).Trim()
                    Version = ($g2[1])
                    Managed = switch([string]($g2[2]).Trim()){'False' {$false} Default {$true}}
                    ManagedQuantifier = switch([string]($g2[2]).Trim()){'False' {0} Default {1}}
                    ManagedValue = [string]($g2[2]).Trim()
                    IsPatch = $g1[1] -imatch 'patch'
                }
                New-Object -TypeName psObject -Property $solutionObject
            }

            do {
                $index = 1
                $pacResponse | %{
                    Write-Host "[ $(($index++)) ]`t" -NoNewline
                    Write-Host "Name: " -NoNewline -ForegroundColor DarkGray; Write-Host "$($_.Name)`t" -NoNewline
                    Write-Host "DisplayName: " -NoNewline -ForegroundColor DarkGray; Write-Host "$($_.DisplayName)`t" -NoNewline
                    Write-Host "Version: " -NoNewline -ForegroundColor DarkGray; Write-Host "$($_.Version)`t" -NoNewline
                    Write-Host "IsPatch: " -NoNewline -ForegroundColor DarkGray; Write-Host "$($_.IsPatch)`t"
                }
                $patchIndex = Read-Host "Select Patch ($((1..$pacResponse.Count) -join ','))"
                $patchSelection = $pacResponse[$patchIndex-1]
            } while ($patchSelection.Name -notin $pacResponse.Name)
            return $patchSelection
        }

    }

    process {

        $pacAuthResponse = & $Global:pptConfig.pacPath auth list

        switch ($pacAuthResponse) {

            {$_ -match 'No profiles were found on this computer'} {
                Write-Host "[ Error ] " -ForegroundColor Yellow -nonewline
                Write-Host "No profiles were found on this computer" -ForegroundColor Yellow
                break
                <#$authResponse = auth
				if ($authResponse) {
                    $IsAuth = $true
                    & $Global:pptConfig.pacPath org select -env $env.env_id
                } else {
                    $IsAuth = $false
                }#>

                <#if (& $Global:pptConfig.pacPath org list | ?{$_ -match '\*'}) {
					$IsAuth = $true
					& $Global:pptConfig.pacPath org select -env $env.env_id
				} else {
					$IsAuth = $false
				}#>
            }

            {$_ -match '\*'} {
                Write-Host "[ Info ] " -ForegroundColor Green -nonewline
                write-host "Authentication profile found" -ForegroundColor Cyan
				& $Global:pptConfig.pacPath org select -env $env.env_id
                $IsAuth = $true}

            #Default {Write-Warning -Message "Unhandled exception"; return}

        }

        Switch($Patch) {
            true {
                if ((& $Global:pptConfig.pacPath org list | ?{$_ -match '\*'}) -match $env.env_id -and $IsAuth) {

                    $patchSolution = GetAvailablePatches
                    $patchSolution

                    Write-Host "[ Info ] " -ForegroundColor Green -nonewline; write-host "Building $(If($Managed){'managed'}else{'unmanaged'}) solution patch" -ForegroundColor Cyan
                    & $Global:pptConfig.pacPath solution export --name $patchSolution.Name -ow --path $Path.path $(if($Managed){'--managed'})
                    & $Global:pptConfig.pacPath solution unpack --zipfile "$($patchSolution.Name)$(If($Managed){'_managed'}).zip" --folder $Path.path -pca --packagetype $(If($Managed){'Managed'}else{'Unmanaged'}) --errorLevel Verbose

                } else {

                    Write-Host '[ Error ] ' -ForegroundColor Yellow -nonewline; write-host 'Fatal exception' -ForegroundColor Red
                    return

                }
            }

            Default {
                if ((& $Global:pptConfig.pacPath org list | ?{$_ -match '\*'}) -match $env.env_id -and $IsAuth) {

                    Write-Host "[ Info ] " -ForegroundColor Green -nonewline; write-host "Building $(If($Managed){'managed'}else{'unmanaged'}) solution" -ForegroundColor Cyan
                    & $Global:pptConfig.pacPath solution export --name $Path.leaf -ow --path $Path.path $(if($Managed){'--managed'})
                    & $Global:pptConfig.pacPath solution unpack --zipfile "$($Path.leaf)$(If($Managed){'_managed'}).zip" --folder $Path.path -pca --packagetype $(If($Managed){'Managed'}else{'Unmanaged'}) --errorLevel Verbose

                } else {

                    Write-Host '[ Error ] ' -ForegroundColor Yellow -nonewline; write-host 'Fatal exception' -ForegroundColor Red
                    return

                }
            }
        }

    }

    end {

        If($SolutionName) {
            $sn = NameThatSolution
            Move-Item -Path (Join-Path -Path $Path.path -ChildPath "$($Path.leaf)$(If($Managed){'_managed'}).zip") -Destination (Join-Path -Path $Path.path -ChildPath "$($sn).zip") -Force -Confirm:$false
        }

    }
}

# EXPORT ALIAS
New-Alias -Name pullSolution -Value Start-PPTSolutionPull -Description 'posh-PowerPlatformToolkit - Start-PPTSolutionPull alias' -Force
