using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace ESuite.UI.E2E.Helpers
{
    public static class WebDriverHelper
    {
        private static IWebDriver? driver;
        private readonly static ConfigHelper configHelper = new();
        public static void InitializeWebDriver()
        {
            driver = CreateWebDriverWithDefaultResolution();
        }

        private static IWebDriver CreateWebDriverWithDefaultResolution()
        {
            ChromeOptions options = new();
            options.AddArgument("window-size=1920,1080");
            options.AddArgument("--enable-javascript");

            if (configHelper.HeadlessMode)
            {
                options.AddArgument("headless");
                options.AddArgument("disable-gpu");
            }
            else
            {
                options.AddArgument("--start-maximized");
            }


            driver = new ChromeDriver(options);
            return driver;
        }

        public static IWebDriver GetWebDriver()
        {
            driver ??= CreateWebDriverWithDefaultResolution();

            return driver;
        }

        public static byte[]? CaptureScreenshot()
        {
            driver ??= GetWebDriver();

            try
            {
                var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                return screenshot.AsByteArray;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error capturing screenshot: {ex.Message}");
                return null;
            }
        }

        public static void QuitWebDriver()
        {
            if (driver != null)
            {
                driver.Quit();
                driver = null;
            }
        }
    }
}
