package net.northking.cctp.testbug.util;

import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.testbug.constants.TestBugError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;

/**
 * @author: puchao.ma
 * @date: 2021/10/19 9:18
 */
public class HTMLToText extends HTMLEditorKit.ParserCallback {

    private final static HTMLToText htmlToText = new HTMLToText();

    private final static Logger logger = LoggerFactory.getLogger(HTMLToText.class);

    private StringBuffer s;

    private void parse(String str) throws IOException {
        InputStream inputStream = new ByteArrayInputStream(str.getBytes());
        Reader reader = new InputStreamReader(inputStream);
        s = new StringBuffer();
        //  the third parameter is true to ignore charset directive
        ParserDelegator delegate = new ParserDelegator();
        delegate.parse(reader, this, Boolean.TRUE);
        inputStream.close();
        reader.close();
    }

    @Override
    public void handleText(char[] data, int pos) {
        s.append(data);
    }

    private String getText() {
        return s.toString();
    }

    public static String getContent(String str) {
        try {
            htmlToText.parse(str);
        } catch (IOException e) {
            logger.error("解析HTML错误", e);
            throw new PlatformRuntimeException(TestBugError.valueOf("解析HTML错误"), e);
        }

        return htmlToText.getText();
    }
}
