package com.screenshot.service;

import com.sun.jna.platform.win32.WinDef.HWND;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ScreenshotService {
    private final Robot robot;
    private final WindowService windowService;
    private final ImageCompareService imageCompareService;

    private static final DateTimeFormatter DATE_FOLDER_FORMAT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FILE_FORMAT =
            DateTimeFormatter.ofPattern("HH-mm-ss");

    public ScreenshotService() throws AWTException {
        this.robot = new Robot();
        this.windowService = new WindowService();
        this.imageCompareService = new ImageCompareService();
    }

    /**
     * Сделать скриншот всего экрана
     */
    public BufferedImage captureFullScreen() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRect = new Rectangle(screenSize);
        return robot.createScreenCapture(screenRect);
    }

    /**
     * Сделать скриншот определённого окна
     */
    public BufferedImage captureWindow(String windowTitle) {
        HWND hwnd = windowService.findWindowByTitle(windowTitle);

        if (hwnd == null) {
            System.out.println("Окно '" + windowTitle + "' не найдено. Делаем скриншот всего экрана.");
            return captureFullScreen();
        }

        // Активируем окно перед скриншотом
        windowService.bringToFront(hwnd);

        // Небольшая задержка для отрисовки
        robot.delay(200);

        Rectangle windowRect = windowService.getWindowRectangle(hwnd);

        if (windowRect == null) {
            System.out.println("Окно минимизировано. Делаем скриншот всего экрана.");
            return captureFullScreen();
        }

        return robot.createScreenCapture(windowRect);
    }

    /**
     * Сделать и сохранить скриншот
     * @return true если скриншот сохранён, false если изображение не изменилось
     */
    public boolean captureAndSave(String basePath, String windowTitle) {
        try {
            BufferedImage screenshot;
            String appName;

            if (windowTitle == null || windowTitle.isEmpty()) {
                screenshot = captureFullScreen();
                appName = "FullScreen";
            } else {
                screenshot = captureWindow(windowTitle);
                // Очищаем имя от недопустимых символов
                appName = sanitizeFileName(windowTitle);
            }

            // Проверяем, изменилось ли изображение
            if (!imageCompareService.hasImageChanged(screenshot)) {
                System.out.println("Изображение не изменилось - пропускаем сохранение");
                return false;
            }

            // Формируем путь: basePath/дата/приложение/
            LocalDateTime now = LocalDateTime.now();
            String dateFolder = now.format(DATE_FOLDER_FORMAT);
            String fileName = "screenshot_" + now.format(TIME_FILE_FORMAT) + ".png";

            Path savePath = Path.of(basePath, dateFolder, appName);
            Files.createDirectories(savePath);

            Path filePath = savePath.resolve(fileName);
            ImageIO.write(screenshot, "png", filePath.toFile());

            System.out.println("Скриншот сохранён: " + filePath);
            return true;

        } catch (IOException e) {
            System.err.println("Ошибка сохранения скриншота: " + e.getMessage());
            return false;
        }
    }

    /**
     * Очистить имя файла от недопустимых символов
     */
    private String sanitizeFileName(String name) {
        return name.replaceAll("[\\\\/:*?\"<>|]", "_")
                .replaceAll("\\s+", "_")
                .substring(0, Math.min(name.length(), 50));
    }

    /**
     * Сбросить состояние сравнения изображений
     */
    public void resetImageComparison() {
        imageCompareService.reset();
    }

    /**
     * Получить список доступных окон
     */
    public java.util.List<String> getAvailableWindows() {
        return windowService.getAllVisibleWindows();
    }
}
