using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using Telegram.Bot;

namespace LC_Bot
{
    internal class Reboot
    {
        private readonly string _ip;
        private int _id;

        EdgeDriver driver;

        public Reboot(string ip)
        {
            _ip = ip;
            var options = new EdgeOptions();
            //options.AddArgument("-headless");
            var service = EdgeDriverService.CreateDefaultService();
            service.HideCommandPromptWindow = true;
            driver = new EdgeDriver(options);
            driver.Manage().Window.Minimize();
        }
        public bool Start()
        {
            using Db db = new Db();
            var o = db.Cams.FirstOrDefault(c => c.Ip == _ip);
            _id = db.Errors.Where(c => c.Ip == _ip && c.Status == "off").First().MsgId;
            if (o != null)
            {
                int port = Convert.ToInt32(o.SwitchPort);
                driver.Navigate().GoToUrl($"http://{o.SwitchConnect}/doc/page/login.asp");
                Thread.Sleep(500);
                try
                {
                    var retext = Program.txt.Replace("<b>‼ НЕИСПРАВНОСТЬ ‼</b>\n", "<b>🔄 ПЕРЕЗАГРУЗКА 🔄</b>\n");
                    Program.botClient.EditMessageTextAsync(6882856105, _id, retext, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
                    var ch = driver.FindElement(By.Id("details-button"));
                    if (ch != null)
                    {
                        driver.FindElement(By.Id("details-button")).Click();
                        driver.FindElement(By.Id("proceed-link")).Click();
                        Thread.Sleep(500);
                    }
                    driver.FindElement(By.Id("username")).SendKeys("admin");
                    driver.FindElement(By.Id("password")).SendKeys("4NUDZhJ7");
                    driver.FindElement(By.XPath("//button[@type='button']")).Click();
                    Thread.Sleep(500);
                    driver.Navigate().GoToUrl($"https://{o.SwitchConnect}/doc/page/switchConfig.asp");
                    Thread.Sleep(1000);
                    var ofnik = driver.FindElement(By.XPath($"//div[contains(@ng-click,'changeSwitch({port - 1}, 4, 4)')]"));
                    ofnik.Click();
                    Thread.Sleep(1000);
                    driver.FindElement(By.XPath("//button[contains(@class,'btn-save')]")).Click();
                    Thread.Sleep(1000);
                    ofnik.Click();
                    Thread.Sleep(1000);
                    driver.FindElement(By.XPath("//button[contains(@class,'btn-save')]")).Click();
                    Thread.Sleep(500);
                    driver.Quit();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else return false;
        }
    }
}
