package com.apobates.forum.thumbnail.handler;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.thumbnail.ThumbConstant;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
/**
 * 使用Thumbnails框架缩放图片.不支持固定尺寸裁剪
 * 
 * @author xiaofanku
 * @since 20191022
 */
public class ThumbnailsScaleHandler extends AbstractCropImageHandler{
	//图片的缩放比例(1-100)
	private final int scale;
	private final static Logger logger = LoggerFactory.getLogger(ThumbnailsScaleHandler.class);
	
	public ThumbnailsScaleHandler(File sourceImagePath, int scale) {
		super(sourceImagePath);
		this.scale = scale;
	}
	
	@Override
	public void cropImage(File cropSaveFile, int width, int height) throws IOException{
		String fileName = getFileName(cropSaveFile); 
		String fileExt = getFileExtension(fileName);
		File sourceImageFile = getOrginalImageFile();
		//
		BufferedImage logoImgBuffer = null;
		try{
			logoImgBuffer = getWatermark();
		}catch(IOException e){}
		if(width > 0 && height > 0){ //固定大小
			if(logger.isDebugEnabled()){
				String descrip = "[Thumbnails]" + ThumbConstant.NEWLINE;
						descrip += "/*----------------------------------------------------------------------*/" +ThumbConstant.NEWLINE;
						descrip += "width: " + width + ", height: " + height + ThumbConstant.NEWLINE;
						descrip += "ext: " + fileExt + ThumbConstant.NEWLINE;
						descrip += "source: " + sourceImageFile.getAbsolutePath() + ThumbConstant.NEWLINE;
						descrip += "thumb: " + cropSaveFile.getAbsolutePath() + ThumbConstant.NEWLINE;
						descrip += "/*----------------------------------------------------------------------*/" + ThumbConstant.NEWLINE;
				logger.debug(descrip);
			}
			//
			Builder<File> b = Thumbnails.of(sourceImageFile).size(width, height);
			if(null!=logoImgBuffer){
				b = b.watermark(getThumbnailPosition(), logoImgBuffer, getWaterBoxOpacity());
			}
			b.outputFormat(fileExt).toFile(cropSaveFile);
		}else{ //自动
			if(logger.isDebugEnabled()){
				String descrip = "[Thumbnails]" + ThumbConstant.NEWLINE;
				descrip += "/*----------------------------------------------------------------------*/" + ThumbConstant.NEWLINE;
				descrip += "scale: " +  scale + ThumbConstant.NEWLINE;
				descrip += "ext: " + fileExt + ThumbConstant.NEWLINE;
				descrip += "source: " + sourceImageFile.getAbsolutePath() + ThumbConstant.NEWLINE;
				descrip += "thumb: " + cropSaveFile.getAbsolutePath() + ThumbConstant.NEWLINE;
				descrip += "/*----------------------------------------------------------------------*/" + ThumbConstant.NEWLINE;
				logger.debug(descrip);
			}
			//
			Builder<File> c = Thumbnails.of(sourceImageFile).scale(Math.abs(scale) / 100.00D);
			if(null!=logoImgBuffer){
				c = c.watermark(getThumbnailPosition(), logoImgBuffer, getWaterBoxOpacity());
			}
			c.outputFormat(fileExt).toFile(cropSaveFile);
		}
	}
}
