package ru.m4mind.managersite.autoupdatemanager.vesta;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import ru.m4mind.checker.Checker;
import ru.m4mind.checker.site.robot.CheckerRobotsClosedIndexing;
import ru.m4mind.checker.site.robot.CheckerVerificationRobots;
import ru.m4mind.checker.site.sitemap.CheckerVerificationSitemap;
import ru.m4mind.managersite.ManagerSites;
import ru.m4mind.managersite.autoupdatemanager.DashboardUpdateManager;
import ru.m4mind.webclient.CreateWebClient;
import ru.m4mind.site.Site;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DashboardVesta extends DashboardUpdateManager {
    private final ManagerSites managerSites;
    private final WebClient webClient;
    private final ArrayList<Checker> checkers;
    private final String url = "https://144.76.72.118:8083";

    public DashboardVesta(ManagerSites managerSites) {
        super(managerSites);
        this.managerSites = managerSites;
        this.webClient = new CreateWebClient().create();


        checkers = new ArrayList<>();
        checkers.add(new CheckerRobotsClosedIndexing());

        authorizationInPanel();
        updateManagerOfDomain();
    }

    public void authorizationInPanel() {
        try {
            HtmlPage page = webClient.getPage(url + "/login/");
            List<HtmlForm> form = page.getForms();
            HtmlForm formElement;
            formElement = form.get(0);
            formElement.getInputByName("user").setValueAttribute("Amado");
            formElement.getInputByName("password").setValueAttribute("TadEKO0Gk5");


            HtmlPage HomePage = formElement.getInputByValue("Войти").click();
            System.out.println("Авторизация в панели управления сайтами Vesta");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void updateManagerOfDomain() {
        System.out.println("Получение актуального списка доменов");
        try {
            HtmlPage page = webClient.getPage(url + "/list/web/");
            List<HtmlElement> listDomains = page.getBody().getElementsByAttribute("div", "class", "l-unit__name");

            for (HtmlElement Domains : listDomains) {
                // Парсим спиосок доменов, на их имена и добавляем их менеджеру
                Site site = new Site("http://www." + Domains.getAttribute("u_name"));
                managerSites.addCheckerSite(site, checkers);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
