
function convertUTF8ToASCII
{
    param ([Parameter(Mandatory = $true, Position = 0)] [String]$utf8Text)
    $utf8TextBytes = [system.text.encoding]::UTF8.GetBytes($utf8Text)
    $asciiText = [system.text.encoding]::convert([text.encoding]::UTF8, [text.encoding]::ASCII, $utf8TextBytes)
    -join [system.text.encoding]::ASCII.GetChars($asciiText)
}

function checkInstitute
{
    param([parameter(position = 0)][string]$instituteSign)
    return $Config.SPK.ContainsKey($instituteSign)
}

function getTimeStamp
{
    param ([Parameter(Mandatory = $false, Position = 0)][string]$formatString = "yyyyMMddHHmmss")   
    $now = Get-Date
    return $now.ToString($formatString)
}

function outLog
{
    $timestamp = Get-Date
    $outString = $timestamp.ToString("HH:mm:ss.mmm") + ": "
    for ($i = 0; $i -lt $args.count; $i++)
    {
        $j = $i + 1
        $outString += $args[$i] 
    }
    if ($previuosTime)
    {
        $outString += ($end - $start)  
    }
    $outString | Tee-Object -FilePath $LogFileName -Append | Write-Host
}
function outScreen
{
    $timestamp = Get-Date
    $outString = $timestamp.ToString("HH:mm:ss.mmm") + ": "
    for ($i = 0; $i -lt $args.count; $i++)
    {
        $j = $i + 1
        $outString += $args[$i] 
    }
    if ($previuosTime)
    {
        $outString += ($end - $start)  
    }
    Write-Host $outString
}

function checkInput
{
    param([parameter(position = 0)][string]$spk)
    $spk = $spk.ToUpperInvariant()
    if ([string]::IsNullOrEmpty($spk))
    {
        if (isProbablyDevelopmentUser)
        {
            Write-Host "no given Institute (parameter '-sparkasse'), using default" $Config.DefaultInstitute
            $spk = $Config.DefaultInstitute.ToUpperInvariant()   
        }
        else
        {
            while ($true)
            {
                $spk = $(Read-Host "please enter Institute Parameter (parameter '-sparkasse'), 'Ctrl-C for exit'" ).ToUpperInvariant()
                if ([string]::IsNullOrEmpty($spk))
                {
                    continue
                }
                elseif (checkInstitute($spk))
                {
                    break
                }
                else
                {
                    Write-Host "this institute is not in our list of wellknown institutes: " 
                    Write-Host ($Config.SPK | Format-Table | Out-String)
                    continue
                }
            }       
        }
    }
    elseif (-not (checkInstitute($spk)))
    {
        # Write-Host "edmond"
        Write-Host "this institute is not in our list of wellknown institutes: " 
        Write-Host ($Config.SPK | Format-Table | Out-String)
        exit  
    }
    return $spk
}

function checkInputSourceFiles
{
    if (-not $InstitutsSourcePath)
    {
        Write-Host "Source file does not exist: " $InstitutsSourcePath 
        return $false
    }
    if (-not $InstitutsSourcePathKURS)
    {
        Write-Host "Source file does not exist: " $InstitutsSourcePathKURS 
        return $false
    }
    return $true
}

function checkInputDataFiles
{
    $ok = $true
    if (-not $ADObjectsFilePath)
    {
        outLog "no ADObjectsFile found !"
        $ok = $false
    }
    if (-not $ADObjectMembershipsFilePath)
    {
        outLog "no ADObjectsFile found !"
        $ok = $false
    }
    if (-not $ADApplicationsInFilePath)
    {
        outLog "no ADApplicationsInFile found !"
        $ok = $false
    }
    if (-not $ADDirectoriesInFilePath)
    {
        outLog "no ADDirectoriesInFile found !"
        $ok = $false
    }
    if (-not $SecurityInFilePath)
    {
        outLog "no SecurityInFile found !"
        $ok = $false
    }
    if (-not $KURSPositionsInFilePath)
    {
        outLog "no KURSPositionsInFile found !"
        $ok = $false
    }
    if (-not $KURSEmployeesInFilePath)
    {
        outLog "no KURSEmployeesInFile found !"
        $ok = $false
    }
    $ADObjectsFileTimeStamp = (Get-ChildItem $ADObjectsFilePath).BaseName.Split("_")[2]
    $ADObjectMembershipsFileTimeStamp = (Get-ChildItem $ADObjectMembershipsFilePath).BaseName.Split("_")[2]
    if ($ADObjectsFileTimeStamp -ne $ADObjectMembershipsFileTimeStamp)
    {
        outLog "TimeStamps of latest input files found are not equal: ADObjectsFileTimeStamp:" $ADObjectsFileTimeStamp "ADObjectMembershipsFileTimeStamp: " $ADObjectMembershipsFileTimeStamp ", stopping process !"
        $ok = $false
    }  
    return $ok  
}

function checkTestMode
{
    if ($Config.TestMode -gt 0)
    {
        outLog "entering TestMode, reading the first" $Config.TestMode "ADObject-entries for every roletype"
        return $true
    }
    outLog "entering ProductionMode, reading all entries"
    return $false
}

function isProbablyDevelopmentUser
{
    $userName = [Environment]::UserName
    if ($userName -ieq "edmond")
    {
        Write-Host "developer" $userName "found"
        return $true
    }
    elseif ($userName -ieq "burgwink")
    {
        Write-Host "developer" $userName "found"
        return $true        
    }
    return $false
}

function dumpVar
{
    param([object]$member)
    Write-Host ($member | Format-Table -Force | Out-String)
}

function dumpConfig
{
    dumpVar($Config)
}

function stringReverse
{
    param ([Parameter(Mandatory = $true, Position = 0)][string]$text)
    $textArray = $Text.ToCharArray()
    [Array]::Reverse($textArray)
    -join $textArray               
}

function stringArrayReverseToCommaSeparatedString
{
    param ([Parameter(Mandatory = $true, Position = 0)] [String[]]$stringArray)
    [Array]::Reverse($stringArray)
    $outString = $stringArray -join ',' | Out-String  
    return $outString         
}
function stringArrayReverseToCommaSeparatedStringReturn
{
    param ([Parameter(Mandatory = $true, Position = 0)] [String[]]$stringArray)
    [Array]::Reverse($stringArray)
    $outString = $stringArray -join ',' | Out-String  
    return $outString         
}
function stringArrayReverseToCommaSeparatedStringWriteOutput
{
    param ([Parameter(Mandatory = $true, Position = 0)] [String[]]$stringArray)
    [Array]::Reverse($stringArray)
    $outString = $stringArray -join ',' | Out-String  
    Write-Output $outString         
}

function stringArrayReverseToCommaSeparatedStringEcho
{
    param ([Parameter(Mandatory = $true, Position = 0)] [String[]]$stringArray)
    [Array]::Reverse($stringArray)
    $stringArray -join ','   
}

function moveToInstituteTmpPath
{
    param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$filePath,
        [Parameter(Mandatory = $false, Position = 1)]
        [bool]$force = $false
    )
    $fileName = [System.IO.Path]::GetFileName($filePath)
    $tmpFilePath = $InstituteRootPathTmp + "/" + $fileName
    if ($force)
    {
        Remove-Item -Path $tmpFilePath -ErrorAction Ignore
    }
    Move-Item -Path $filePath -Destination $InstituteRootPathTmp
    return $tmpFilePath
}

function convertUTF8ToASCII
{
    param ([Parameter(Mandatory = $true, Position = 0)][string]$text) 
    $utf8Text = [system.text.encoding]::UTF8.GetBytes($text)
    $asciiText = [system.text.encoding]::convert([text.encoding]::UTF8, [text.encoding]::ASCII, $utf8Text)
    -join [system.text.encoding]::ASCII.GetChars($asciiText)
}


function writeExceptionInfoReduced
{
    param([Parameter(Mandatory)][System.Management.Automation.ErrorRecord]$ErrorRecord)
    Write-Host "=== EXCEPTION ===" -ForegroundColor Red
    Write-Host "Message : $($ErrorRecord.Exception.Message)" -ForegroundColor Red
    Write-Host "Type    : $($ErrorRecord.Exception.GetType().FullName)" -ForegroundColor Yellow
    Write-Host $ErrorRecord.InvocationInfo.PositionMessage
    Write-Host "ScriptStackTrace:" -ForegroundColor Yellow
    Write-Host $ErrorRecord.ScriptStackTrace
}

function writeExceptionInfo
{
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [System.Management.Automation.ErrorRecord]$ErrorRecord,
        [switch]$Rethrow
    )

    Write-Host "=== EXCEPTION ===" -ForegroundColor Red
    Write-Host "Message : $($ErrorRecord.Exception.Message)" -ForegroundColor Red
    Write-Host "Type    : $($ErrorRecord.Exception.GetType().FullName)" -ForegroundColor Yellow
    Write-Host $ErrorRecord.InvocationInfo.PositionMessage
    Write-Host "ScriptStackTrace:" -ForegroundColor Yellow
    Write-Host $ErrorRecord.ScriptStackTrace

    if ($Rethrow)
    {
        throw $ErrorRecord
    }
}