BNMoldovaCurrency.psm1

function Get-BNMConfig {
    <#
        .SYNOPSIS
        Get the default configuration for BNM.

        .DESCRIPTION
        Get the default configuration for Banca Nationala of Moldova.

        .EXAMPLE
        Get-BNMConfig
    #>


    [CmdletBinding()]
    Param()

    try {
        Write-Verbose -Message 'Getting content of config.json and returning as a PSCustomObject.'
        $config = Get-Content -Path "$PSScriptRoot\config.json" -ErrorAction 'Stop' | ConvertFrom-Json
        
        $map = $config.bnm.params |% {
            $_.Psobject.Members | where-object membertype -like 'noteproperty';
        }
        $map |
            where-object value -match '^\$' |
                ForEach-Object { $_.value = Invoke-Expression $($_.value) }
        
        # idea from https://www.powershellmagazine.com/2019/06/14/pstip-a-better-way-to-generate-http-query-strings-in-powershell/
        # Create a http name value collection from an empty string
        $nvCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
     
        $map | ForEach-Object { $nvCollection.Add($_.name, $_.value) }
        
        # Build the uri
        $uriRequest = [System.UriBuilder]$config.bnm.endPoint
        $uriRequest.Query = $nvCollection.ToString()
        
        return $uriRequest.Uri.OriginalString
    } catch {
        throw "Can't find the JSON configuration file. Use 'Set-BNMConfig' to create one."
    }
}
function Get-BNMCurrency {
    <#
        .SYNOPSIS
        Gets BNM currency for specified date.

        .DESCRIPTION
        Invokes HTTP GET method to the BNM server for reading exchange rates based on configuration file.
        
        .EXAMPLE
        Get-BNMCurrency
        Returns whole list of available rates from Banca Nationala.

        .EXAMPLE
        Get-BNMCurrency |? { CharCode -match 'EUR' }
        Returns data only for EURO currency.

        .EXAMPLE
        Get-BNMCurrency |? { CharCode -match 'EUR' } |% Value
        Returns float value representing exchange rate in MDL (1 EUR = xx.xx MDL)

        .EXAMPLE
        Get-BNMCurrency |% CharCode
        Returns list of supported currencies.

        .EXAMPLE
        Get-BNMCurrency | select CharCode, Value
        Returns a table representing a map from currency and value.
        
        .EXAMPLE
        Get-BNMCurrency | select CharCode, Value | convertto-csv -notypeinformation | sc rates.csv
        Saves exchange rates into csv file.
    #>


    [CmdletBinding()]
    Param ()

    Write-Verbose -Message 'Starting Get-BNMCurrency.'

    $url = Get-BNMConfig -ErrorAction 'SilentlyContinue'
    
    $data = [xml] $(Invoke-RestMethod $url)
    
    $fname = "{0}_{1}.xml" -f $(New-TemporaryFile).FullName, $MyInvocation.MyCommand.Name;
    
    $data.Save($fname);

    $returnObj = $data.ValCurs.Valute;
    
    Write-Verbose -Message 'Exiting Get-BNMCurrency.'

    return $returnObj
}
function Save-BNMCurrency {
    <#
        .SYNOPSIS
        Saves BNM currency for specified date.

        .DESCRIPTION
        Uses Get-BNMCurrency to get data.
        
        .EXAMPLE
        Save-BNMCurrency
        Saves into default filename.
        
        .EXAMPLE
        Save-BNMCurrency -Filename today.csv
        Saves into specified filename.
    #>


    [CmdletBinding()]
    Param (
        [ValidateNotNullOrEmpty()]
        [String]
        $Filename
    )
    
    Get-BNMCurrency | ConvertTo-Csv -NoTypeInformation | Set-Content $Filename

}
function Set-BNMConfig {
    <#
        .SYNOPSIS
        Set the default configuration for Banca Nationala of Moldova.

        .DESCRIPTION
        Set the default configuration for BNM server. Convert parameter values to object and write to the JSON configuration file.

        .PARAMETER Endpoint
        The URI endpoint that will be utilized.

        .PARAMETER Params
        The params that will be appended to the URI.
        
        .EXAMPLE
        Set-BNMConfig -Endpoint "https://bnm.md/ro/official_exchange_rates" -Params "@{get_xml = 1; date = '01.01.2020'}"
        Sets the default addr to "bnm.md" with query param "get_xml=1&date=01.01.2020".

        .EXAMPLE
        Set-BNMConfig -Endpoint "https://localhost/get_currency"
        Used in case of proxy-ing bnm.md results via nginx or alternative proxy.
        Also can be used in test environments.
        Sets the default addr to "localhost" without query param.

    #>


    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [String]
        $Endpoint,
        $Params
    )

    try {
        Write-Verbose -Message 'Trying Get-BNMConfig before Set-BNMConfig.'
        $config = Get-Content -Path "$PSScriptRoot\config.json" -ErrorAction 'Stop' |
            ConvertFrom-Json
        Write-Verbose -Message 'Stored config.json found.'
    } catch {
        Write-Verbose -Message 'No configuration found - starting with default configuration.'
        $config = @{
            bnm = @{
                endPoint = "https://bnm.md/ro/official_exchange_rates"; 
                params=@(
                    @{get_xml=1}; 
                    @{date="`$(get-date -f 'dd.MM.yyyy')"}
                )
            }
        }
    }

    if ($Endpoint) {$config.bnm.endpoint = $Endpoint}
    if ($Params) {$config.bnm.params = $Params}

    Write-Verbose -Message 'Setting config.json.'
    $config |
        ConvertTo-Json -Depth 99 |
            Set-Content -Path "$PSScriptRoot\config.json"
}