using System.Diagnostics;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

namespace Berufsschule_HAM.E2ETests.Helper;

public static class LocationsHelper
{
    public static void CreateLocation(ChromeDriver driver, string name, string room, string seat)
    {
        NavigateToLocationsPage(driver);
        IWebElement createLocationButton = driver.FindElement(By.CssSelector("button[data-bs-target=\"#createModal\"]"));
        createLocationButton.Click();
        AppHelper.AwaitVisible(driver, By.Id("createLocationName"));
        driver.FindElement(By.Id("createLocationName")).SendKeys(name);
        driver.FindElement(By.Id("createRoomNumber")).SendKeys(room);
        driver.FindElement(By.Id("createSeat")).SendKeys(seat);
        IWebElement createButton = driver.FindElement(By.CssSelector("#createModal .btn-primary"));
        createButton.Click();
        Assert.True(AppHelper.TryRetryFindSuccessToast(driver));
    }

    public static void UpdateLocation(ChromeDriver driver, string name, string room, string seat, string newName, string newRoom, string newSeat)
    {
        NavigateToLocationsPage(driver);
        string selector = $"button.btn-warning[data-location-name=\"{name}\"][data-room-number=\"{room}\"][data-seat=\"{seat}\"]";
        IWebElement updateLocationButton = driver.FindElement(By.CssSelector(selector));
        AppHelper.ScrollIntoViewAndClick(driver, updateLocationButton);
        AppHelper.AwaitVisible(driver, By.Id("editLocationName"));
        List<string[]> ids = [["editLocationName", newName], ["editRoomNumber", newRoom], ["editSeat", newSeat]];
        ids.ForEach(id =>
        {
            var cnInput = driver.FindElement(By.Id(id[0]));
            cnInput.Click();
            cnInput.Clear();
            cnInput.SendKeys(id[1]);
        });
        IWebElement updateButton = driver.FindElement(By.CssSelector("#editModal .btn-warning"));
        updateButton.Click();
        Assert.True(AppHelper.TryRetryFindSuccessToast(driver));
    }


    public static void DeleteLocation(ChromeDriver driver, string cn)
    {
        NavigateToLocationsPage(driver);
        IWebElement deleteButton = driver.FindElement(By.CssSelector($"button.btn-danger[data-location-id=\"{cn}\"]"));
        AppHelper.ScrollIntoViewAndClick(driver, deleteButton);
        AppHelper.AwaitVisible(driver, By.Id("deleteModal"));
        driver.FindElement(By.Id("deleteModal"));
        IWebElement deleteConfirmButton = driver.FindElement(By.Id("deleteForm"));
        deleteConfirmButton.Click();
        Assert.True(AppHelper.TryRetryFindSuccessToast(driver));
    }
    
    public static void NavigateToLocationsPage(ChromeDriver driver)
    {
        driver.Navigate().GoToUrl(new Uri(AppHelper.ServerUri, "/Home/Locations"));
    }
}