Locality.psm1

function Get-Locality {
    <#
    .SYNOPSIS
    This cmdlet attempts to parse out locations from the input
 
    .DESCRIPTION
    By default, the cmdlet is loaded with many countries, all 50 US states, and some cities. You can extend or overwrite each of these lists.
 
    The cmdlet will then attempt to guess each state, country, land (larger than single country), area (something within a state), region (something within a country), and city.
 
    It will create an object and leave any unresolved text available for review
 
    Countries sourced from: https://www.nationsonline.org/oneworld/countries_of_the_world.htm
    States sourced from: https://abbreviations.yourdictionary.com/articles/state-abbrev.html
    Capitols sourced from: https://www.50states.com/tools/thelist.htm
    Largest Cities sourced from: https://www.mymove.com/city-guides/compare/largest-us-cities/
 
    .PARAMETER InputObject
    The string to parse
 
    .PARAMETER Overwrite
    A hashtable containing one or more of the following keys: lands,countries,regions,states,areas,cities. Will replace any inbuilt lists with the values found in each key.
 
    .PARAMETER Append
    A hashtable containing one or more of the following keys: lands,countries,regions,states,areas,cities. Will append to any inbuilt lists with the values found in each key.
 
    .EXAMPLE
    PS> "NYC" | Get-Locality
 
    Land :
    Country : United States
    Region :
    State : New York
    Area :
    City : New York City
    Unknown :
 
    .EXAMPLE
    PS> Get-Locality Reno
 
    Land :
    Country :
    Region :
    State :
    Area :
    City :
    Unknown : Reno
 
    This example shows what happens when a location is unknown
 
    .EXAMPLE
    PS> Get-Locality -Append @{cities=@{name="Reno"}} Reno
 
    Land :
    Country :
    Region :
    State :
    Area :
    City : Reno
    Unknown :
 
    This example shows how you can append a list of city hashtables to the cities list to recognize specific cities
 
    .EXAMPLE
    PS> Get-Locality -Append @{cities=@{name="Reno";state="Nevada"}} Reno
 
    Land :
    Country : United States
    Region :
    State : Nevada
    Area :
    City : Reno
    Unknown :
 
    This example shows how tying a city to a state allows the state to get resolved to a country
 
        .EXAMPLE
    PS> Get-Locality "Carson City"
 
    Land :
    Country : United States
    Region :
    State : Nevada
    Area :
    City : Carson City
    Unknown :
 
    This example showcases how any state capitol is a known city and can be resolved to larger geo units
 
    .EXAMPLE
    PS> Get-Locality "Carson City" -Overwrite @{cities=@{}}
 
    Land :
    Country :
    Region :
    State :
    Area :
    City :
    Unknown : Carson City
 
    This example shows how overriding the cities list can make inbuilt known locations no longer known.
 
    .EXAMPLE
    PS> "Phoenix,Arizona","Switzerland","Ghana,Accra","Central America","Phoenix,Arizona,USA","England","Pacific NorthWest","pnw","Austin","Georgia" | Get-Locality |ft -auto
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
                    United States Arizona Phoenix
                    Switzerland
                    Ghana Accra
    Central America
                    United States Arizona Phoenix
                    United Kingdom England
                    United States Pacific North West
                    United States Pacific North West
                    United States Texas Austin
                    United States Georgia
 
    This example shows how abbreviations are all converted to the same base name and how any known locations resolve to their larger known geographic units as well.
 
    .NOTES
    ### Known Issue ###
    Georgia sucks. We will always assume that the state of georgia is meant, not the country:
 
    PS> Get-Locality "Georgia","Tbilisi,Georgia","Atlanta,Georgia"| ft
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
         United States Georgia
         United States Georgia Tbilisi
         United States Georgia Atlanta
 
    If you are using Georgia the country, you'll need to use the local name or the name Georgia_Country like so:
 
    PS> Get-Locality "Georgia","Tbilisi,Sakartvelo","Tbilisi,Georgia_Country","Atlanta,Georgia"| ft
 
    Land Country Region State Area City Unknown
    ---- ------- ------ ----- ---- ---- -------
         United States Georgia
         Georgia_Country Tbilisi
         Georgia_Country Tbilisi
         United States Georgia Atlanta
 
    #>

    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline, Mandatory)]
        $InputObject,
        [hashtable]$Overwrite,
        [hashtable]$Append
    )

    begin {
        # Dynamically load any existing json files to populate these lists
        "lands", "countries", "regions", "states", "areas", "cities" | ForEach-Object {
            # If runtime doesn't want to use the existing file (-Overwrite), use their param instead
            if ($PSBoundparameters.Overwrite.$_) {
                [array]$obj = $PSBoundparameters.Overwrite.$_
            }
            elseif (Test-Path $PSScriptRoot\$_.json) {
                [array]$obj = Get-ChildItem $PSScriptRoot\$_.json | ForEach-Object { Get-Content $_.Fullname } | ConvertFrom-Json
            }
            else {
                # At least need an array object to add to
                [array]$obj = @()
            }

            # If runtime wants to add extra items to the list, they should get added here
            if ($PSBoundparameters.Append.$_) {
                $obj += $PSBoundparameters.Append.$_
            }

            # Need to ensure that we have only 1 entry in the list with the same value in the property "name"
            # Needs to be case insensitive detection and needs to not get sorted
            $out = [ordered]@{}
            $obj | Where-Object { $_.Name } | ForEach-Object {
                if (-not $out.Contains($_.Name)) {
                    $out.Add($_.Name, [PSCustomObject]$_)
                }
            }

            Set-Variable -Name $_ -Value $out.values

            # Get any external modules or commands that should get executed before or after processing
            $script:modules = @(Get-Module).Where{ $_.PrivateData -and $_.PrivateData.ContainsKey("Locality") }
            if (-not [string]::IsNullOrWhiteSpace($Locality_Pre)) {
                $script:pre = $Locality_Pre
            }
            else {
                $script:pre = ""
            }
            if (-not [string]::IsNullOrWhiteSpace($Locality_Post)) {
                $script:post = $Locality_Post
            }
            else {
                $script:post = ""
            }
        }
    }
    process {
        foreach ($item in $InputObject) {
            $item = Invoke-Hook -HookType Pre -InputObject $item
            $item = [Locality]::New($item, $Lands, $Countries, $Regions, $States, $Areas, $Cities)
            $item = Invoke-Hook -HookType Post -InputObject $item
            $item
        }
    }
}
class Locality {
    [string]$Land
    [string]$Country
    [string]$Region
    [string]$State
    [string]$Area
    [string]$City
    [string]$Unknown
    hidden [System.Collections.Generic.List[string]]$Leftover

    Locality([string]$Location, $Lands, $Countries, $Regions, $States, $Areas, $Cities) {
        # Need to split the base string into some basic components
        $this.Leftover = ($Location.Trim() -split "[,;:|]+ *").Trim()

        # Prioritize country over state, state over area, etc.
        $SearchOrder = @(
            @{name = "Country"; variable = "Countries" }
            @{name = "State"; variable = "States" }
            @{name = "Area"; variable = "Areas" }
            @{name = "Land"; variable = "Lands" }
            @{name = "Region"; variable = "Regions" }
            @{name = "City"; variable = "Cities" }
        )
        foreach ($item in $SearchOrder) {
            $names = "Land", "Country", "Region", "State", "Area", "City"
            $obj = Get-Variable $item.variable -ValueOnly
            $name = $item.name

            # Search all properties in all objects in the list except for the properties that get assigned on match ($names)
            $properties = $obj |
            ForEach-Object { $_.PSObject.Properties.Name } |
            Select-Object -Unique |
            Where-Object { $_ -notin $names }
            Write-Verbose "Searching properties: $properties"

            foreach ($property in $properties) {
                if ($this.Leftover -and -not $this.$name) {
                    Write-Verbose "Listing $name - $property"
                    # Create match list of the unmatched properties
                    if ($results = $obj | Where-Object { $_.$property -match "^$($this.Leftover -join '$|^')$" }) {
                        $this.$name = $results.name | Select-Object -First 1
                        "Found ${name} (for property- $property): {0}" -f $this.$name | Write-Verbose
                        $this.RemoveLeftover(($results.$property | Select-Object -First 1))
                        # If match found, check the $names properties on that object and set other data on the output object accordingly
                        foreach ($name in $names) {
                            if ($results.$name -and -not $this.$name) {
                                $this.$name = $results.$name | Select-Object -First 1
                                "Found context ($name): {0}" -f $this.$name | Write-Verbose
                                $this.RemoveLeftover($this.$name)
                            }
                        }
                    }
                    elseif ($name -eq "State") {
                        # States often get added to a line without any separater (e.g. `Boston MA`, `Tala Fla.`, or `Des Moines Iowa`)
                        # If the line ends with any state matches, peel that state part off the line
                        if ($results = $obj | Where-Object { $this.Leftover -match " $($_.$property -join '$| ')$" }) {
                            $this.$name = $results.name
                            "Found ${name}: {0}" -f $this.$name | Write-Verbose
                            $item, $rest = $this.Leftover.Where({ $_ -match " $($Results.$property)$" }, "Split", 1)
                            $this.Leftover = $rest
                            $this.Leftover.Add(($item -replace " $($Results.$property)"))
                            $this.Leftover = $this.Leftover | Where-Object { $_ }
                        }
                    }
                }
            }
            # When searching for state,
            # Washingtonions say state to remove ambiguity with Wash DC.
            # Their state should always end up as just the state name
            if ($name -eq "State" -and $this.Leftover -like "Washington State") {
                $results = $this.Leftover -like "Washington State" | Select-Object -First 1
                $this.$name = "Washington"
                "Found state match {0}" -f $this.$name | Write-Verbose
                $this.RemoveLeftover($results)
            }
            # When searching for area,
            # If any lefover lines end in ` county`, call that an area and remove.
            elseif ($name -eq "Area" -and -not $this.$name) {
                if ($results = $this.Leftover | Where-Object { $_ -match " County$" }) {
                    $this.$name = $results | Select-Object -First 1
                    "Found fuzzy match ($name): {0}" -f $this.$name | Write-Verbose
                    $this.RemoveLeftover($this.$name)
                }
            }
        }

        # When state is good and there are still leftovers, assign the leftover to the area.
        if ($this.State -and $this.Leftover) {
            $item = $this.Leftover | Select-Object -First 1
            $this.Leftover.Remove($item)
            if ([string]::IsNullOrWhiteSpace($this.Area)) {
                $this.Area = $item
                "Found (fuzzy) Area: {0}" -f $this.Area | Write-Verbose
            }
            else {
                $this.Unknown = $item
                "Found (fuzzy) Unkown: {0}" -f $this.Unknown | Write-Verbose
            }
        }

        # After the base searching is all done, do another pass with cities, states, and countries
        # Try to add the larger locations if the more specific location is known
        $this.ResolveLocations($Countries, $States, $Cities)

        # Leftover isn't a pretty object on output (its a list, not an array)
        # So Leftover has been set to hidden
        # Unknown which is an array is output instead
        if ($this.Leftover) {
            if ([string]::IsNullOrWhiteSpace($this.Unknown)) {
                $this.Unknown = $this.Leftover -join ", "
            }
            else {
                $this.Unknown += ", " + ($this.Leftover -join ", ")
            }
        }
    }

    RemoveLeftover([string]$item) {
        # Create a scriptblock with a here-string that contains a here-string to protect against injection accidents
        $sb = @"
param(`$i)
`$i -eq @"
$item
`"@
"@

        $sb = [scriptblock]::Create($sb)

        # Arrays.Remove() methods are all case sensitive. But FindIndex with a scriptblock predicate can choose NOT to be.
        # Use FindIndex with the sb above to do a case insensitive search for the input $item and then remove it from the array.
        if (($index = $this.Leftover.FindIndex($sb)) -ne -1) {
            Write-Verbose "found index $index"
            $this.Leftover.RemoveAt($index)
        }
        else {
            Write-Verbose "found no index for item $item"
        }
    }

    ResolveLocations($Countries, $States, $Cities) {

        if ($this.City -and -not $this.State) {
            # Cities that have a known state can be assigned to that state.
            if ($result = $Cities | Where-Object { $_.Name -eq $this.City -and $_.State }) {
                $this.State = $result.State
            }
        }
        if ($this.State -and -not $this.Country) {
            # States that have a known country can be assigned to that country.
            if ($result = $States | Where-Object { $_.Name -eq $this.State -and $_.Country }) {
                $this.Country = $result.Country
            }
        }
    }

    [string] ToString() {
        $output = ""
        @(
            "Unknown"
            "City"
            "Area"
            "State"
            "Region"
            "Country"
            "Land"
        ) | ForEach-Object {
            if (-not [string]::IsNullOrWhiteSpace($this.$_)) {
                $output += ", " + $this.$_
            }
        }
        return $output.Trim(', ')
    }
}
function Invoke-Hook {
    # This function has two parts: Processing to do if there are module hooks and processing for a command hook
    [CmdletBinding()]
    param(
        [ValidateSet("Pre", "Post")]
        [Parameter(Mandatory)]
        [string]$HookType,

        $InputObject
    )

    # Part one: Module Hooks
    foreach ($mi in $script:modules) {
        try {
            # Only run if the hashtable pre/post properties exist and are set with actual text
            if (-not [string]::IsNullOrWhiteSpace($mi.PrivateData["Locality"][$HookType])) {
                Write-Verbose "Executing command $($mi.Name)\$($mi.PrivateData["Locality"][$HookType]) with data $InputObject"
                $InputObject = & "$($mi.Name)\$($mi.PrivateData["Locality"][$HookType])" $InputObject
            }
        }
        catch {
            Write-Warning "Failed to execute command '$($mi.Name)\$($mi.PrivateData["Locality"][$HookType])' with data $InputObject"
        }
    }

    # Part two: Command Hook
    # Need to use an if/else because script scope with dynamic text seems hard ($script:$HookType)
    if ($HookType -eq "Pre") {
        $command = $script:Pre
    }
    else {
        $command = $script:Post
    }
    # Don't need to validate -not [string]::IsNullOrWhiteSpace here because we already did that in the Begin block of the public function
    if ($command) {
        Write-Verbose "Executing command $command with data $InputObject"
        $InputObject = & $command -InputObject $InputObject
    }

    # Part three: Push data to the output stream
    $InputObject
}