using Berufsschule_HAM.E2ETests.Helper;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using System.Diagnostics;
using xRetry;

namespace Berufsschule_HAM.E2ETests;

public class AssetsPageTests : IDisposable
{
    private readonly ChromeDriver _driver;
    public Uri serverUri;
    public string serverUrl;
    public Process serverProcess;

    public AssetsPageTests()
    {
        serverUrl = AppHelper.ServerUrl;
        serverUri = AppHelper.ServerUri;
        Task<Process> app = AppHelper.StartApp(serverUrl);
        _driver = AppHelper.GetChromeDriver();
        serverProcess = app.Result;
    }

    [RetryFact(5)]
    public void AssetsPage_ShouldShowButton()
    {
        AppHelper.Login(_driver);
        AssetsHelper.NavigateToAssetsPage(_driver);
        _driver.FindElement(By.CssSelector("button[data-bs-target=\"#createAssetModal\"]"));
    }

    [RetryFact(5)]
    public void AssetsPage_ShouldShowCreateViewModal()
    {
        AppHelper.Login(_driver);
        AssetsHelper.NavigateToAssetsPage(_driver);
        _driver.FindElement(By.CssSelector("button[data-bs-target=\"#createAssetModal\"]")).Click();
        List<string> ids = ["createName", "createLocationSelect", "createUsersSelect", "createSerialNumber", "createPresetSelect", "createPresetApply", "createType", "createMake", "createModel", "attributesContainer", "addAttributeBtn", "createPurchaseDate", "createPurchaseValue", "createPurchaseAt", "createPurchaseBy"];
        List<string> css = ["#createAssetModal .btn-primary", "#createAssetModal .btn-secondary"];
        ids.ForEach(id => _driver.FindElement(By.Id(id)));
        css.ForEach(selector => _driver.FindElement(By.CssSelector(selector)));
    }

    [RetryFact(5)]
    public void AssetsPage_ShouldCreateAndShowDetailAndUpdateAndDeleteAsset()
    {
        AppHelper.Login(_driver);
        AssetsHelper.NavigateToAssetsPage(_driver);
        AssetsHelper.CreateAsset(_driver);
        IWebElement row = _driver.FindElement(By.CssSelector("tr.asset-row:last-of-type"));
        int id = Convert.ToInt32(row.GetAttribute("data-asset-id"));
        _driver.ExecuteJavaScript($"$('tr[data-asset-id=\"{id}\"]').click()");
        AppHelper.AwaitVisible(_driver, By.Id("viewAssetModal"));
        _driver.FindElement(By.Name("Barcode"));
        var inputs = _driver.FindElements(By.CssSelector("#viewAssetModal input"));

        var emptyInputs = inputs
            .Where(i => string.IsNullOrWhiteSpace(i.GetAttribute("value")))
            .ToList();

        Assert.Empty(emptyInputs);
        AssetsHelper.UpdateAsset(_driver, row);
        AssetsHelper.DeleteAsset(_driver, row);
    }

    public void Dispose()
    {
        _driver.Quit();
        serverProcess.Kill();
    }
}
