package com.lanyuanxiaoyao.bookstore;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 * @author lanyuanxiaoyao
 * @version 20251031
 */
@Slf4j
public class BookCrawlerTest {
  public static void main(String[] args) throws IOException {
    ChromeDriver driver = null;
    try {
      driver = new ChromeDriver(
          new ChromeDriverService.Builder()
              .usingDriverExecutable(new File("/Users/lanyuanxiaoyao/SynologyDrive/tools/chromium/134/macOS-1345775/chromedriver"))
              .build(),
          new ChromeOptions()
              .setBinary(new File("/Users/lanyuanxiaoyao/SynologyDrive/tools/chromium/134/macOS-1345775/Chromium.app/Contents/MacOS/Chromium"))
              .addArguments(
                  // 允许不安全的域名
                  "--allow-insecure-localhost",
                  // 禁用GPU渲染，headLess 模式用不上
                  "--disable-gpu",
                  // 禁用音频输出
                  "--disable-audio-output",
                  // 禁用错误页自动重新刷新
                  "--disable-auto-reload",
                  // 禁用默认应用加载
                  "--disable-default-apps",
                  // 禁用浏览器扩展
                  "--disable-extensions",
                  // 禁用日志
                  "--disable-logging",
                  // 禁用通知
                  "--disable-notifications",
                  // 禁用远程字体
                  "--disable-remote-fonts",
                  // 禁用弹出窗口
                  "--disable-popup-blocking",
                  // 禁用同步
                  "--disable-sync",
                  // 禁用沙盒
                  "--no-sandbox",
                  // 禁用声音
                  "--mute-audio",
                  // 禁止图片显示
                  "blink-settings=imagesEnabled=false"
              )
      );
      var articleUrl = "https://www.alicesw.com/novel/32007.html";
      driver.get(articleUrl);
      var contextUrl = driver.findElement(By.xpath("//div[@class='book_newchap']//a[contains(text(),'查看所有章节')]")).getDomProperty("href");
      if (StrUtil.isBlank(contextUrl)) {
        throw new RuntimeException("获取目录页链接失败");
      }
      driver.get(contextUrl);
      var chapterItems = driver.findElements(By.cssSelector("ul.mulu_list > li > a"))
          .stream()
          .map(element -> element.getDomProperty("href"))
          .toList();
      for (var index = 0; index < chapterItems.size(); index++) {
        var chapterUrl = chapterItems.get(index);
        if (StrUtil.isBlank(chapterUrl)) {
          throw new RuntimeException("获取章节链接失败: " + chapterUrl);
        }
        driver.get(chapterUrl);
        var text = driver.findElement(By.cssSelector(".read-content")).getText();
        log.info(text);

        var title = driver.getTitle();
        if (StrUtil.isBlank(title)) {
          title = String.valueOf(index);
        }
        var filename = StrUtil.format("{}.txt", title.replaceAll("\\s", "_"));
        var targetFile = Path.of("out2", filename);
        Files.deleteIfExists(targetFile);
        Files.createFile(targetFile);
        Files.writeString(targetFile, text);

        ThreadUtil.safeSleep(2000);
      }
    } finally {
      if (driver != null) {
        driver.close();
      }
    }
  }
}
