package com.apobates.forum.utils.fileupload.ckeditor;

import java.util.HashMap;
import java.util.Map;

import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.fileupload.AbstractHandler;
import com.google.gson.Gson;
/**
 * CKeditor V4.11.4上传的回调句柄
 * @author xiaofanku
 * @since 20190613
 */
public class CKEditorHightHandler extends AbstractHandler{
	private final long allowMaxFileBytes;
	
	/**
	 * 
	 * @param frontVisitPath    
	 * @param allowMaxFileBytes 限制文件上传的大小,单位字节
	 */
	public CKEditorHightHandler(String frontVisitPath, long allowMaxFileBytes) {
		super(frontVisitPath);
		this.allowMaxFileBytes = allowMaxFileBytes;
	}
	
	/**
	 * 不限制文件上传的大小,表示代码不作上传前的检查.交由容器
	 * @param frontVisitPath
	 */
	public CKEditorHightHandler(String frontVisitPath) {
		super(frontVisitPath);
		this.allowMaxFileBytes = -1;
	}
	
	@Override
	public String getResponse(String fileName, String callFunction) {
		return getFrontVisitPath()+fileName;
	}

	@Override
	public String generateFileName() {
		return "snapshot-" + DateTimeUtils.getDateFullFormatString() + ".png";
	}

	@Override
	public long allowMaxBytes() {
		return allowMaxFileBytes;
	}
	
	/**
	 * CK4:V4.11.4的响应格式
	 * {@link https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html}
	 * 
	 * @param isCompleted 是否完成上传
	 * @param message     消息内容
	 * @param fileName    保存的文件
	 * @param imageUrl    上传成功后的访问地址
	 * @return
	 */
	public static String buildCkeditorResponse(boolean isCompleted, String message, String fileName, String imageUrl){
		Map<String, Object> data = new HashMap<>();
		data.put("uploaded", isCompleted ? "1" : "0");
		if (null!=fileName) {
			data.put("fileName", fileName);
		}
		if (null!=imageUrl) {
			data.put("url", imageUrl);
		}
		if (!isCompleted) {
			Map<String,String> tmp = new HashMap<>();
			tmp.put("message", Commons.optional(message, "未知的网络错误"));
			data.put("error", tmp);
		}
		return new Gson().toJson(data);
	}
	
	/**
	 * CK4:V4.11.4的失败的响应格式
	 * {@link https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html}
	 * 
	 * @param isCompleted 是否完成上传
	 * @param message     错误消息内容
	 * @return
	 */
	public static String buildCkeditorResponse(boolean isCompleted, String message){
		return buildCkeditorResponse(isCompleted, message, null, null);
	}
}
