package dev.ksan.etfoglasiserver.service;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import dev.ksan.etfoglasiserver.model.Entry;
import dev.ksan.etfoglasiserver.model.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

@Component
public class ScraperOld implements Runnable {

  @Autowired SubjectAltService altService;
  @Autowired EntryService entryService;

  private WebClient webClient;
  private volatile boolean running = true;

  public ScraperOld() {
    this.webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
  }

  private static String getTextOrEmpty(HtmlElement parent, String xPath) {
    HtmlElement element = parent.getFirstByXPath(xPath);
    return element == null ? "" : element.asNormalizedText();
  }

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");

  private void configureHtmlUnitLogging() {
    Logger htmlUnitLogger = Logger.getLogger("com.gargoylesoftware.htmlunit");
    htmlUnitLogger.setLevel(Level.SEVERE);
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.SEVERE);
    htmlUnitLogger.addHandler(consoleHandler);
  }

  @Override
  public void run() {
    configureHtmlUnitLogging();
    while (running && !Thread.currentThread().isInterrupted()) {

      try {
        System.out.println("Performing WebClient task...");

        HtmlPage mainPage = webClient.getPage("https://efee.etf.unibl.org/oglasi/");
        webClient.waitForBackgroundJavaScript(1000);

        List<DomElement> rawToggles = mainPage.getByXPath("//a[@href='#']");
        List<HtmlAnchor> toggles = new ArrayList<>();
        for (DomElement el : rawToggles) {
          if (el instanceof HtmlAnchor) {
            toggles.add((HtmlAnchor) el);
          }
        }
        int ul_idSelection = 1;
        for (HtmlAnchor anchor : toggles) {
          HtmlElement span = anchor.getFirstByXPath(".//span[@class='ui-btn-text']");
          if (span == null) continue;  // skip anchors with no text span

          // Skip “clear text” buttons
          String spanText = span.asNormalizedText().toLowerCase();
          if (spanText.contains("clear text")) continue;

          // Only get direct text nodes (skip child span with collapse text)
          List<DomText> textNodes = span.getByXPath("./text()");
          StringBuilder sb = new StringBuilder();
          for (DomText textNode : textNodes) {
            sb.append(textNode.asNormalizedText());
          }
          String groupName = sb.toString().trim();

          System.out.println("Group name: " + groupName);

          HtmlPage updatedPage = anchor.click();
          webClient.waitForBackgroundJavaScript(1000);

          String ul_id = "ul_id_" + Integer.toString(ul_idSelection);

          DomElement rawElement = updatedPage.getElementById(ul_id);
          HtmlElement listElement =
              rawElement instanceof HtmlElement ? (HtmlElement) rawElement : null;

          if (listElement == null) {
            // System.out.println("An element with id " + ul_id + " was not found");
            ul_idSelection++;
            continue;
          }

          List<HtmlElement> items = listElement.getElementsByTagName("li");
          for (HtmlElement item : items) {
            String title = getTextOrEmpty(item, ".//h1");
            String date = getTextOrEmpty(item, ".//h2[1]");
            String info = getTextOrEmpty(item, ".//h2[2]");
            List<String> paragraphs = new ArrayList<>();
            List<HtmlElement> pTags = item.getByXPath(".//p");
            String filepath = null; // default
            for (HtmlElement pTag : pTags) {
              paragraphs.add(pTag.asNormalizedText());

              // check if this <p> contains an <a> link
              HtmlAnchor aTag = pTag.getFirstByXPath(".//a");
              if (aTag != null) {
                filepath = aTag.getHrefAttribute();
              }
            }

            Subject subjectid = altService.findSubjectIdWithTitle(title);
            Entry entry =
                new Entry(
                    title.trim(),  groupName, LocalDateTime.parse(date, formatter),
                        info, paragraphs, filepath, subjectid);

            System.out.println("Subject  "+entry.getTitle());
            System.out.println();


            entryService.addEntry(entry);
          }

          ul_idSelection++;
        }

         Thread.sleep(300000);

      } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Error in webscraper");
      } finally {
        this.webClient.close();
      }
    }
    System.out.println("WebScraper thread stopped");
  }

  public void stop() {
    running = false;
  }
}
