. "$PSScriptRoot/Config.ps1";
. "$PSScriptRoot/../Types/InstallerAction.ps1";

$null = New-Module {
    . "$PSScriptRoot/../Types/InstallerAction.ps1";
    $userArgument = "name";

    function Start-SoftwareInstaller {
        param(
            [string] $Name,
            [scriptblock] $Installer = { },
            [scriptblock] $Configurator = { },
            [scriptblock] $UserConfigurator = { },
            [InstallerAction] $Action = [InstallerAction]::Install,
            [hashtable] $Arguments
        )

        if (-not $Name) {
            $Name = Split-Path -Leaf (Split-Path -Parent ((Get-PSCallStack)[1].ScriptName));
        }

        if ($null -ne $Name) {
            $Name = "``$Name``";
        } else {
            $Name = "unknown software";
        }

        $installHandler = {
            param(
                [InstallerAction] $Action,
                [hashtable] $Arguments
            )

            $Arguments ??= @{ };

            $argumentList = @{
                installer = $installHandler;
                arguments = $Arguments;
            };

            if ($action -eq ([InstallerAction]::Install)) {
                Write-Host "Installing $Name…";
                & $Installer @argumentList;
            } elseif ($Action -eq ([InstallerAction]::Configure)) {
                Write-Host "Configuring $Name…";
                & $Configurator @argumentList;

                foreach ($user in Get-Users) {
                    $Arguments.Add($userArgument, $user);
                    $argumentList.Add("action", [InstallerAction]::ConfigureUser);
                    & $installHandler @argumentList;
                }
            } elseif ($Action -eq ([InstallerAction]::ConfigureUser)) {
                if ((-not $Arguments.ContainsKey($userArgument)) -or ($null -eq $Arguments[$userArgument])) {
                    $argumentList.Add($userArgument, ($env:UserName));
                }

                Write-Host "Configuring $Name for user ``$($Arguments[$userArgument])``…";
                & $UserConfigurator @argumentList;
            }
        };

        & $installHandler -Action $Action -Arguments $Arguments;
    }
}