using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;

namespace LC_ConfigCamer
{
    internal class Selenium_Work
    {
        public string[] Ip_list { get; set; }
        public string Old_pass { get; set; }
        public string New_Pass { get; set; }

        FirefoxDriver driver;
        public Selenium_Work(string[] ip, string old_pass, string new_pass)
        {
            Ip_list = ip;
            Old_pass = old_pass;
            New_Pass = new_pass;

        }

        public async void Start()
        {
            FirefoxOptions options = new FirefoxOptions();
            //options.AddArgument("-headless");
            FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
            service.HideCommandPromptWindow = true;
            driver = new FirefoxDriver(Environment.CurrentDirectory, options);

            for (int i = 0; i < Ip_list.Count(); i++)
            {
                driver.Navigate().GoToUrl($"http://{Ip_list[i]}");
                await Form1.Log_add($"Открыл Web-интерфейс камеры {Ip_list[i]}");
                Thread.Sleep(500);

                #region Ввод логин пароль
                driver.FindElement(By.XPath("//*[@id=\"username\"]")).SendKeys("admin");
                driver.FindElement(By.XPath("//*[@id='password']")).SendKeys(Old_pass);
                try
                {
                    driver.FindElement(By.XPath("//*[@id=\"login\"]/table/tbody/tr/td[2]/div/div[5]/button")).Click();
                }
                catch (Exception)
                {
                    MessageBox.Show("Не нашел XPath кнопки входа");
                }
                await Form1.Log_add($"Ввел логин и пароль");
                    Thread.Sleep(2000);
                #endregion

                if (CheckXPath("/html/body/div[2]/table/tbody/tr/td[2]/div/div[2]/div/label"))
                {
                    await Form1.Log_add($"Не правильный пароль к {Ip_list[i]}", true);
                    await Form1.Log_add($"===================================", true);
                    continue;
                }
                else
                {
                    #region Переход в конфигурацию
                    driver.Navigate().GoToUrl($"http://{Ip_list[i]}/doc/page/config.asp");
                    await Form1.Log_add($"Перешел в режим конфигурации");
                    Thread.Sleep(1000);
                    #endregion


                    #region Выбрать пользователя и нажать ИЗМЕНИТЬ
                    driver.FindElement(By.Name("user")).Click();
                    await Form1.Log_add($"Перешел в настройки пользователей");
                    Thread.Sleep(1000);
                    if (CheckXPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[2]/div/div[2]/div"))
                        driver.FindElement(By.XPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[2]/div/div[2]/div")).Click();
                    else
                        MessageBox.Show("Ткнуть на строку admin");
                    Thread.Sleep(500);
                    if (CheckXPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[1]/span[2]/button[2]"))
                        driver.FindElement(By.XPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[1]/span[2]/button[2]")).Click();
                    //else if (await CheckXPath("/html/body/div[3]/div[1]/div/div/div[1]/div/div/div[1]/span[2]/button[2]"))
                    //    driver.FindElement(By.XPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[1]/span[2]/button[3]")).Click();
                    //else if (await CheckXPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[1]/span[2]/button[2]"))
                    //    driver.FindElement(By.XPath("/html/body/div[4]/div[1]/div/div/div[1]/div/div[1]/div[1]/span[2]/button[3]")).Click();
                    else
                        MessageBox.Show("Ткнуть изменить");
                    await Form1.Log_add($"Открыл изменение настроек пользователя");
                    Thread.Sleep(1000);
                    #endregion


                    #region Изменение пароля
                    if (CheckXPath("/html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[2]/div/div[1]/div[4]/div[1]/span[2]/input"))
                    {
                        var el = driver.FindElement(By.XPath("/html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[2]/div/div[1]/div[4]/div[1]/span[2]/input"));
                        el.Clear(); el.SendKeys(Old_pass);
                        await Form1.Log_add($"Ввел старый пароль");
                    }
                    else
                    {
                        MessageBox.Show("Ввод старого пароля");
                    }

                    if (CheckXPath("/html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[2]/div/div[1]/div[4]/div[2]/span[2]/input"))
                    {
                        var el = driver.FindElement(By.XPath("/html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[2]/div/div[1]/div[4]/div[2]/span[2]/input"));
                        el.Clear(); el.SendKeys(New_Pass);
                        el = driver.FindElement(By.XPath("/html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td[2]/div/div[1]/div[4]/div[4]/span[2]/input"));
                        el.Clear(); el.SendKeys(New_Pass);
                        await Form1.Log_add($"Ввел 2 раза новый пароль");
                    }
                    else
                    {
                        MessageBox.Show("Ввод нового пароля");
                    }
                    driver.FindElement(By.XPath("//html/body/div[1]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[3]/td/div/button[1]")).Click(); 
                    await Form1.Log_add($"Сохранил изменения.");
                    await Form1.Log_add($"===================================");
                    #endregion
                    continue;
                }

            }

            driver.Quit();
        }

        private bool CheckXPath(string xPath)
        {
            try
            {
                _ = driver.FindElement(By.XPath(xPath));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
