package ru.mcs.udk.utils;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DocumentUtils {
    private static volatile Tesseract instance;

    public static Tesseract getInstance() {
        Tesseract localInstance = instance;
        if (localInstance == null) {
            synchronized (Tesseract.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new Tesseract();
                    instance.setDatapath("program\\tesseract\\tessdata\\");;
                    instance.setLanguage("rus");
                }
            }
        }
        return localInstance;
    }

    public static void main(String[] args) {
        Tesseract tesseract = getInstance();

        try {
            String text = tesseract.doOCR(new File("book3.PNG"));
            System.out.println(text);
            String udk = findUDK(text);
            System.out.println("UDK " + udk);
        } catch (TesseractException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static String getText(BufferedImage image) throws TesseractException {
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("d:\\program\\Tesseract-OCR\\tessdata\\");
        tesseract.setLanguage("rus");
        tesseract.setVariable("user_defined_dpi", "300");
        // Настройки для маленьких изображений
        // tesseract.setPageSegMode(7); // PSM_SINGLE_LINE (распознавание одной строки)
        // tesseract.setVariable("tessedit_min_characters", "1"); // Минимальное количество символов

        return tesseract.doOCR(image);
    }

    public static String findUDK(String text) {
        // Регулярное выражение для поиска УДК
        Pattern pattern = Pattern.compile("[Уу]\\s*[Дд]\\s*[Кк]\\s*([0-9.]+)");
        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static boolean isCyrillic(String fileName) {
        String regex = ".*[\\p{IsCyrillic}]{3,}.*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(fileName);
        return matcher.matches();
    }
}
