package com.apobates.forum.trident.tag;

import java.io.IOException;
import java.util.Optional;
import java.util.ResourceBundle;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.apobates.forum.attention.core.ImagePathCoverter;
import com.apobates.forum.utils.Commons;
/**
 * 输出图片的缩略图路径
 * @author xiaofanku
 * @since 20191103
 */
public class ThumbImagePathTag extends SimpleTagSupport{
	private String path;
	private String scale="auto";
	//
	private final String imageBucketDomain;
	private final String uploadImageDirectName;
	
	public ThumbImagePathTag(){
		ResourceBundle gisResource = ResourceBundle.getBundle("global");
		this.imageBucketDomain = gisResource.getString("img.bucket.domain");
		this.uploadImageDirectName=gisResource.getString("img.bucket.upload.direct");
	}
	
	public void setPath(String path) {
		this.path = path;
	}

	public void setScale(String scale) {
		this.scale = scale;
	}

	@Override
	public void doTag() throws JspException, IOException {
		if(!Commons.isNotBlank(path)){
			getJspContext().getOut().print("/static/img/140x140.png");
			return;
		}
		ImagePathCoverter ipc = new ImagePathCoverter(path);
		String imagePath = "/static/img/140x140.png";
		Optional<String> data = ipc.decodeUploadImageFilePath(imageBucketDomain, uploadImageDirectName);
		if(data.isPresent()){
			String[] pathInfo = getPathInfo(data.get());
			imagePath = String.format("%s/thumbs/%s/%s/%s", imageBucketDomain, pathInfo[0], scale, pathInfo[1]);
		}
		getJspContext().getOut().print(imagePath);
	}
	/**
	 * 获得目录名和文件名
	 * 
	 * @param decodeImagePath
	 * @param directoryEnum
	 * @return
	 */
	private String[] getPathInfo(String imageFilePath){
		String lookUploadImgPrefix = imageBucketDomain+"/"+uploadImageDirectName;
		String[] pathData = imageFilePath.replace(lookUploadImgPrefix, "").split("/");
		String[] data = {"/", ""}; //[0]=目录,[1]=文件名
		//
		if(pathData.length == 3){
			data[0]=pathData[1];
			data[1]=pathData[2];
		}
		if(pathData.length == 2){
			data[1]=pathData[1];
		}
		return data;
	}
}
