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 UsersPageTests : IDisposable
{
    private readonly ChromeDriver _driver;
    public Uri serverUri;
    public string serverUrl;
    public Process serverProcess;

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

    [RetryFact(5)]
    public void UsersPage_ShouldShowButton()
    {
        AppHelper.Login(_driver);
        UsersHelper.NavigateToUsersPage(_driver);
        _driver.FindElement(By.CssSelector("button[data-bs-target=\"#createModal\"]"));
    }

    [RetryFact(5)]
    public void UsersPage_ShouldShowCreateViewModal()
    {
        AppHelper.Login(_driver);
        UsersHelper.NavigateToUsersPage(_driver);
        _driver.FindElement(By.CssSelector("button[data-bs-target=\"#createModal\"]")).Click();
        List<string> ids = ["createTitle", "createName", "createSurname", "createBirthDate", "createCity", "createStreet", "createStreetNr", "createWorkplace", "createGroups", "createPassword", "createPhotoFile", "createJpegPhoto", "createPhotoPreview"];
        List<string> css = ["#createModal .btn-primary", "#createModal .btn-secondary"];
        ids.ForEach(id => _driver.FindElement(By.Id(id)));
        css.ForEach(selector => _driver.FindElement(By.CssSelector(selector)));
    }

    [RetryFact(5)]
    public void UsersPage_ShouldCreateAndShowDetailAndUpdateAndDeleteUser()
    {
        AppHelper.Login(_driver);
        UsersHelper.NavigateToUsersPage(_driver);
        UsersHelper.CreateUser(_driver);
        _driver.ExecuteJavaScript($"$('tr.user-row:last-of-type').click()");
        AppHelper.AwaitVisible(_driver, By.Id("detailModal"));
        var inputs = _driver.FindElements(By.CssSelector("#detailModal input"));
        var emptyInputs = inputs
            .Where(i => string.IsNullOrWhiteSpace(i.GetAttribute("value")))
            .ToList();
        Assert.Empty(emptyInputs);
        _driver.ExecuteJavaScript($"$('#detailModal .btn-close').click()");


        UsersHelper.UpdateUser(_driver);
        UsersHelper.DeleteUser(_driver);
    }

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