using Berufsschule_HAM.E2ETests.Helper;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using SeleniumExtras.WaitHelpers;
using System.Diagnostics;
using xRetry;

namespace Berufsschule_HAM.E2ETests;

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

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

    [RetryFact(5)]
    public void HomePage_ShouldShowLoginPage()
    {
        _driver.Navigate().GoToUrl(serverUrl);
        IWebElement loginForm = _driver.FindElement(By.CssSelector("form[action=\"/Home/Login\"]"));
        Assert.True(loginForm.Displayed);
    }

    [RetryFact(5)]
    public void HomePage_ShouldSucceedLogin()
    {
        AppHelper.Login(_driver);
        Assert.Contains("/Home/Index", _driver.Url);
    }

    [RetryFact(5)]
    public void HomePage_ShouldSucceedLoginAndLogout()
    {
        AppHelper.Login(_driver);
        Assert.Contains("/Home/Index", _driver.Url);
        IWebElement userDropdown = _driver.FindElement(By.Id("userDropdown"));
        userDropdown.Click();
        IWebElement logout = _driver.FindElement(By.CssSelector("a[href=\"/Home/Logout\"]"));
        Assert.True(logout.Displayed);
        logout.Click();
        AppHelper.Timeout(_driver).Until(ExpectedConditions.UrlContains("/Home/Login"));
        Assert.Contains("/Home/Login", _driver.Url);
    }

    [RetryFact(5)]
    public void HomePage_ShouldContainButtons()
    {
        _driver.Navigate().GoToUrl(new Uri(serverUri, "/Home/Index"));
        AppHelper.Login(_driver);

        _driver.FindElement(By.CssSelector("a[href=\"/Home/Inventory\"]"));
        _driver.FindElement(By.CssSelector("a[href=\"/Home/Assets\"]"));
        _driver.FindElement(By.CssSelector("a[href=\"/Home/Locations\"]"));
        _driver.FindElement(By.CssSelector("a[href=\"/Home/Users\"]"));
        _driver.FindElement(By.CssSelector("a[href=\"/Home/Groups\"]"));
    }

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