param(
    [Parameter(Mandatory=$true)]
    $githubToken,
    [Parameter()]
    $numberToBuild,
    [parameter(Mandatory=$true)]
    [string]$buildId,
    [parameter(Mandatory=$true)]
    [string]$repositoryFolder,
    [Parameter()]
    [string]$webhookEndpoint
)

if ($numberToBuild -eq "-1") {
    $numberToBuild = ""
}

$versions = @("dev", "cloud-release")
if (-not (Test-Path "$($PSScriptRoot)/previous")) {
    New-Item -ItemType Directory -Path "$($PSScriptRoot)/previous"
}

foreach ($version in $versions) {
    $response = Invoke-RestMethod -Uri "http://ishq-buildserver.insitesofthosting.com:8111/guestAuth/app/rest/builds?locator=branch:$($version),status:SUCCESS,buildType:Insitecommerce_BlueprintBuilder"
    $id = $response.builds.FirstChild.Attributes["id"].Value

    $url = "http://ishq-buildserver.insitesofthosting.com:8111/guestAuth/repository/download/Insitecommerce_BlueprintBuilder/$($id):id/errors.json"

    Invoke-WebRequest -Uri $url -OutFile "$($PSScriptRoot)/previous/$($version).json"
}

docker build . -f bb.Dockerfile --build-arg GITHUB_TOKEN=$githubToken --build-arg CACHE_BUST=New-Guid -t blueprint-builder --build-arg NUMBER_TO_BUILD=$numberToBuild
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}
docker create --name get-output blueprint-builder
docker cp get-output:/output ./blueprintBuilder
docker rm get-output

if (!$webhookEndpoint) {
    Write-Output "Build complete but no webhook endpoint provided"
    exit
}

$breakingChangesList = [System.Collections.Arraylist]::New()

$comparedToDev = Get-Content "$($PSScriptRoot)/output/comparedTo-dev.json" | ConvertFrom-Json
$newErrors = @{}
$comparedToDev.newErrors.psobject.properties | Foreach { $newErrors[$_.Name] = $_.Value }

$keys = Write-Output $newErrors | Select-Object -ExpandProperty Keys

foreach ($errorKey in $keys) {
    $extraInfo = ""
    for ($i = 0; $i -lt 1 -and $i -lt $newErrors[$errorKey].Length; $i++) {   
        $extraInfo += "`n`n## $($newErrors[$errorKey][$i].fileName)`n`n``````$($newErrors[$errorKey][$i].codeSnippet)"
    }
    $errorMessage = $errorKey
    if ($errorMessage.Length -gt 300) {
        $errorMessage = $errorKey.substring(0, 300);
    }

    $groupedBlueprints = Write-Output $newErrors[$errorKey] | Group-Object -Property clientName,blueprintName

    $errorCount = $newErrors[$errorKey].Length
    $blueprintCount = $groupedBlueprints.Length

    
    $breakingChangesList.Add(@{
        "name" = "$($errorCount) Error$(IF ($errorCount -gt 1) {'s'} ELSE {''}) In $($blueprintCount) Blueprint$(IF ($blueprintCount -gt 1) {'s'} ELSE {''})"
        "value" = "$($errorMessage)`n`n# Code $($extraInfo)"
    })
}

if ($breakingChangesList.Length -le 0) {
    Write-Output "No new errors"
    exit
}

$messageSet = $breakingChangesList[0..9]
$jsonBody = [PSCustomObject][Ordered]@{
    "@type" = "MessageCard"
    "@context" = "http://schema.org/extensions"
    "summary" = "Blueprint Builder Breaking Changes"
    "themeColor" = '0078D7'
    "sections" = @(
    @{
        "activityTitle" = "Spire Breaking Changes (Showing $($messageSet.Length) of $($breakingChangesList.Count))"
        "activitySubtitle" = "Spire Breaking Changes for $repositoryFolder"
        "activityImage" = "https://blog.codinghorror.com/content/images/uploads/2007/03/6a0120a85dcdae970b0128776ff992970c-pi.png"
        "facts" = $messageSet
        "markdown" = $true
    }
    )
    "potentialAction" = @(
    @{
        "@type" = "OpenUri"
        "name" = "View in TeamCity"
        "targets" = @(
        @{
            "os" = "default"
            "uri" = "http://ishq-buildserver.insitesofthosting.com:8111/buildConfiguration/Insitecommerce_BlueprintBuilder/$($buildId)?buildTab=artifacts"
        }
        )
    }
    )
}

$messageBody = ConvertTo-Json $jsonBody -Depth 10

$parameters = @{
    "URI" = $webhookEndpoint
    "Method" = 'POST'
    "Body" = $messageBody
    "ContentType" = 'application/json'
}
if ($messageSet.Count -gt 0) {
    Invoke-RestMethod @parameters
}
