#!/bin/bash
. "$PSScriptRoot/Context.ps1";

if (-not ("OpenQA.Selenium.Firefox.FirefoxDriver" -as [type])) {
    if ((Get-Package Selenium.WebDriver -ErrorAction "SilentlyContinue")) {
        $zipFile = [System.IO.Compression.ZipFile]::OpenRead((Get-Package Selenium.WebDriver).Source);
        $stream = [System.IO.MemoryStream]::new();
        $reader = [System.IO.StreamReader]($zipFile.Entries[2]).Open();
        $reader.BaseStream.CopyTo($stream);
        [byte[]]$bytes = $stream.ToArray();
        $reader.Close();
        $zipFile.Dispose();
        $null = [System.Reflection.Assembly]::Load($bytes);
    }
}

function Start-CustomDownload() {
    param(
        [Context] $context,
        [string] $url,
        [Action[OpenQA.Selenium.Firefox.FirefoxDriver]] $action,
        [string] $outDir = $null
    )

    $tempDir = $context.GetTempDirectory();
    $options = [OpenQA.Selenium.Firefox.FirefoxOptions]::new();
    $options.SetPreference("browser.download.folderList", 2);
    $options.SetPreference("browser.download.dir", $tempDir);
    # $options.AddArgument("--headless");

    $downloadChecker = {
        param()

        $files = Get-ChildItem $tempDir;

        if ($(@($files)).Count -gt 0) {
            foreach ($file in Get-ChildItem $tempDir) {
                try {
                    $stream = [System.IO.File]::Open($file.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None);

                    if ($stream) {
                        $stream.Close();
                    }

                }
                catch  {
                    return $true;
                }
            }

            return $false;
        } else {
            return $true;
        }
    }

    $browser = [OpenQA.Selenium.Firefox.FirefoxDriver]::new($options);
    $browser.Navigate().GoToUrl($url);
    $action.Invoke($browser);

    while ($downloadChecker.Invoke()) {
        Write-Information "Waiting for download to finish...";
        Start-Sleep 1;
    }

    $file = Get-ChildItem $tempDir;

    if (-not $outDir) {
        $outDir = ".";
    }

    $result = Move-Item $file $outDir -PassThru;
    $browser.Quit();
    Remove-Item -Recurse $tempDir;
    return $result;
}

function Start-AutomatedDownload() {
    param(
        [Context] $context,
        [string] $url,
        [string] $buttonSelector,
        [string] $outDir = $null
    )

    $action = {
        param([OpenQA.Selenium.Firefox.FirefoxDriver] $browser)
        $browser.FindElement([OpenQA.Selenium.By]::CssSelector("$buttonSelector")).Click();
    }

    return Start-CustomDownload $context $url $action $outDir;
}