package com.apobates.forum.attention.core;

import java.util.Optional;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 表情图片的路径句柄
 * Schema(smile://)
 * @author xiaofanku
 * @since 20190307
 */
public class SmileyImagePathConvertHandler implements ImagePathDecodeHandler, ImagePathEncodeHandler{
	//smiley
	private final String smileyDirectName;
	
	//smile://
	public SmileyImagePathConvertHandler(String siteDomain, String smileyDirectName) {
		this.smileyDirectName = smileyDirectName;
	}

	@Override
	public Optional<String> decode(String content, ImageDirectoryEnum directoryEnum, String scale) {
		String lookSmileyPrefix = "smile://"+directoryEnum.name().toLowerCase();
		String replaceSmileyPrefix = "/"+smileyDirectName;
		Document doc = Jsoup.parse(content);
		Elements imgTags = doc.select("img[src]");
		for(Element element : imgTags){
			String oldSrc = element.attr("src");
			if(oldSrc.startsWith(lookSmileyPrefix)){
				element.attr("src", oldSrc.replace(lookSmileyPrefix, replaceSmileyPrefix).toLowerCase());
			}
		}
		return Optional.ofNullable(doc.body().html());
	}

	@Override
	public Optional<String> encode(String content, ImageDirectoryEnum directoryEnum) {
		String lookSmileyPrefix = "/"+smileyDirectName;
		String replaceSmileyPrefix = "smile://"+directoryEnum.name().toLowerCase();
		Document doc = Jsoup.parse(content);
		Elements imgTags = doc.select("img[src]");
		for(Element element : imgTags){
			String oldSrc = element.attr("src");
			if(oldSrc.startsWith(lookSmileyPrefix)){
				element.attr("src", oldSrc.replace(lookSmileyPrefix, replaceSmileyPrefix).toLowerCase());
			}
		}
		return Optional.ofNullable(doc.body().html());
	}

}
