package com.baidu.ueditor.extend;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import org.json.JSONObject;

import java.util.Base64;
import java.util.Map;

public final class UEBase64Uploader {

	public static State save(String fileName, Map<String, Object> conf, UeditorService ueditorService) {
	    // String filedName = (String) conf.get("fieldName");
		// String fileName = request.getParameter(filedName);
		byte[] data = decode(fileName);

		long maxSize = (Long) conf.get("maxSize");

		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		String suffix = FileType.getSuffix("JPG");

		// String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename"));
		State storageState = ueditorService.saveBinaryFile(data, conf.get("filename") + suffix);
		
		//savePath = savePath + suffix;
		//String rootPath = ConfigManager.getRootPath(request,conf);
		//String physicalPath = rootPath + savePath;
		//State storageState = StorageManager.saveBinaryFile(data, physicalPath);

		if (storageState.isSuccess()) {
			try {
				JSONObject jsonObj = new JSONObject(storageState.toJSONString());
				//storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("url", jsonObj.getString("url"));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return storageState;
	}

	private static byte[] decode(String content) {
		return Base64.getDecoder().decode(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}
	
}