package com.search.supersearch.service;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 喜欢番茄火锅
 * @date 2023/10/17 10:43
 */
@Service
@Slf4j
public class TikaService {
    final private static Pattern pattern = Pattern.compile("\\s*|\\t|\\r|\\n");

    @SneakyThrows
    public String parser(File file, Metadata metadata) {


        Parser parser = new AutoDetectParser();

        BodyContentHandler handler = new BodyContentHandler(-1);
        FileInputStream inputstream = null;
        try {
            inputstream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ParseContext context = new ParseContext();

        parser.parse(inputstream, handler, metadata, context);

        //getting the list of all meta data elements
//        String[] metadataNames = metadata.names();

//        for (String name : metadataNames) {
//            System.out.println(name + ": " + metadata.get(name));
//        }

        String s = handler.toString();
        if (s != null) {

            Matcher m = pattern.matcher(s);
            return m.replaceAll("");

        }
        return handler.toString();
    }

    @SneakyThrows
    public String parser(URL url, Metadata metadata) {


        Parser parser = new AutoDetectParser();

        BodyContentHandler handler = new BodyContentHandler();
        InputStream inputstream = null;
        try {
            inputstream = TikaInputStream.get(url);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ParseContext context = new ParseContext();

        parser.parse(inputstream, handler, metadata, context);

//        String s = handler.toString();
//        if (s != null) {
//            Matcher m = pattern.matcher(s);
//            return m.replaceAll("\\s*|\\t|\\r|\\n","");
//
//        }
        return handler.toString();
    }
}
