package com.apobates.forum.attention.core.decorater;

import com.apobates.forum.attention.ImageDirectoryEnum;
import com.apobates.forum.attention.core.UploadImagePathConvert;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.Optional;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 适用内容中含有多个图片的转换,例如:回复内容
 * 
 * @author xiaofanku
 * @since 20200516
 */
public class MultiUploadImagePathCovert {
    private final UploadImagePathConvert uploadImageConvert;
    private final static Logger logger = LoggerFactory.getLogger(MultiUploadImagePathCovert.class);
    
    public MultiUploadImagePathCovert(String imageDomain, String uploadImageDirectName) {
        this.uploadImageConvert = new UploadImagePathConvert(imageDomain, uploadImageDirectName);
    }
    /**
     * 编码内容的图片地址,ImageDirectoryEnum等于:DEFAT
     * 
     * @param content 若内容为null抛出NPE
     * @return 
     */
    public String encode(String content){
        return encode(content, ImageDirectoryEnum.DEFAT);
    }
    /**
     * 编码内容的图片地址
     * 
     * @param content 若内容为null抛出NPE
     * @param directoryEnum 图片目录的存储形式: 默认:存储到bucket;本地:存储到应用站内,适用于内置的会员头像
     * @return 
     */
    public String encode(String content, ImageDirectoryEnum directoryEnum){ //20200717
        Objects.requireNonNull(content);
        if(null == directoryEnum){
            return content;
        }
        String lookUploadImgPrefix = getImageDomain() + "/" + getImageUploadDirectName(); //http://center.test.com/imagestore
        //
        Document doc = Jsoup.parseBodyFragment(content);
        Elements imgTags = doc.select("img[src]");
        for (Element element : imgTags) {
            String oldSrc = element.attr("src");
            if (oldSrc.startsWith(lookUploadImgPrefix)) {
                try{
                    String encodeImageURL = uploadImageConvert.encode(new URL(oldSrc), directoryEnum).orElse(null); 
                    if(null != encodeImageURL){
                        element.attr("src", encodeImageURL);
                    }
                }catch(MalformedURLException e){
                    if(logger.isDebugEnabled()){
                        logger.debug("encode multi image path fail", e);
                    }
                }
            }
        }
        return doc.body().html();
    }
    /**
     * 解码内容中的图片地址,ImageDirectoryEnum等于:DEFAT
     * 
     * @param content 若内容为null抛出NPE
     * @param lazyLoad 是否延迟加载
     * @param scale 图片的尺寸
     * @return 
     */
    public String decode(String content, boolean lazyLoad, String scale){
        return decode(content, ImageDirectoryEnum.DEFAT, lazyLoad, scale);
    }
    /**
     * 解码内容中的图片地址
     * 
     * @param content 若内容为null抛出NPE
     * @param directoryEnum 图片目录的存储形式: 默认:存储到bucket;本地:存储到应用站内,适用于内置的会员头像
     * @param lazyLoad 是否延迟加载
     * @param scale 图片的尺寸
     * @return 
     */
    public String decode(String content, ImageDirectoryEnum directoryEnum, boolean lazyLoad, String scale){ //20200717
        Objects.requireNonNull(content);
        if(null == directoryEnum){
            return content;
        }
        
        String lookUploadImgPrefix = "image://" + directoryEnum.name().toLowerCase();
        //图片的尺寸@ADD
        logger.info("[SCALE][UploadImagePathConvertHandler]image scale: " + scale);
        String checkScale = uploadImageConvert.checkImageScale(scale);
        logger.info("[SCALE][UploadImagePathConvertHandler]thumb scale: " + checkScale);
        Document doc = Jsoup.parseBodyFragment(content);
        Elements imgTags = doc.select("img[src]");
        for (Element element : imgTags) {
            String oldSrc = element.attr("src");
            if (oldSrc.startsWith(lookUploadImgPrefix)) {
                try{
                    Optional<URL> dip = uploadImageConvert.decode(oldSrc, directoryEnum, scale);
                    if(dip.isPresent()){
                        if (lazyLoad) {
                            element.attr("class", "lazyload")
                            .attr("src", "data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs=")
                            .attr("data-scale", "resize")
                            .attr("data-original", dip.get().toString());
                        } else {
                            element.attr("src", dip.get().toString());
                        }
                    }
                }catch(MalformedURLException e){
                    if(logger.isDebugEnabled()){
                        logger.debug("decode multi image path fail", e);
                    }
                }
            }
        }
        return doc.body().html();
    }
    
    public String getImageDomain(){
        return uploadImageConvert.getImageDomain();
    }
    public String getImageUploadDirectName(){
        return uploadImageConvert.getUploadDirectName();
    }
}