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.Optional;
import java.util.regex.PatternSyntaxException;

/**
 * 实体图标地址的解码器
 * 
 * @author xiaofanku
 * @since 20200830
 */
public class ForumEntityIcoDecorder {
    private final UploadImagePathConvert uploadImageConvert;
    
    public ForumEntityIcoDecorder(String imageDomain, String uploadImageDirectName) {
        this.uploadImageConvert = new UploadImagePathConvert(imageDomain, uploadImageDirectName);
    }
    
    /**
     * 解码编码后的实体图标地址, ImageDirectoryEnum等于:DEFAT
     * 
     * @param imageEncodeURL 已经编码的图片地址,允许为null
     * @param scale 图片的尺寸,若为null表示自动
     * @return 
     * @throws java.net.MalformedURLException 
     */
    public Optional<URL> decode(String imageEncodeURL, String scale) throws MalformedURLException{
        if(null == imageEncodeURL){
            return Optional.empty();
        }
        //原始: /thumbs/%s/%s/%s
        Optional<URL> dp = uploadImageConvert.decode(imageEncodeURL, ImageDirectoryEnum.DEFAT, scale);
        //转成: /cover?water=0&dir=%s&scale=%s&file=%s
        if(!dp.isPresent()){
            return Optional.empty();
        }
        try{
            String[] pArr = dp.get().toString().split("/");
            String data = String.format("%s/cover?water=0&dir=%s&scale=%s&file=%s", uploadImageConvert.getImageDomain(), pArr[4], pArr[5], pArr[6]);
            return Optional.of(new URL(data));
        }catch(PatternSyntaxException | IndexOutOfBoundsException e){
            return Optional.empty();
        }
    }
}