package jp.sourceforge.shovel.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlUtil {
    static int flags;
    static Pattern[] patterns;

    static {
        flags = Pattern.CASE_INSENSITIVE;
        patterns = new Pattern[] {
            Pattern.compile("<head.*?</head.*?>", flags),
            Pattern.compile("<script.*?</script.*?>", flags),
            Pattern.compile("<!--.*?-->", flags),
            Pattern.compile("<[^>]*?>", flags),
            Pattern.compile("\\s+", flags),
            Pattern.compile("　+", flags),
            Pattern.compile("\\t+", flags),
        };
    }

    public static String stripTags(String html) {
        for( Pattern pattern : patterns ) {
            Matcher matcher = pattern.matcher(html);
            html = matcher.replaceAll("");
        }
        Pattern pattern = Pattern.compile("(\\r?\\n)+", flags);
        Matcher matcher = pattern.matcher(html);
        html = matcher.replaceAll("\\n");
        pattern = Pattern.compile("　\\r?\\n", flags);
        matcher = pattern.matcher(html);
        html = matcher.replaceAll("\\n");
        html.replace("&amp;", "&");
        html.replace("&lt;", "<" );
        html.replace("&gt;", ">" );
        html.replace("&nbsp;", " " );
        html.replace("&#...;", "");
        return html;
    }
}
