package com.app.admin.common.ueditor.upload;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.FileType;
import com.app.admin.common.ueditor.define.State;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.utils.file.UploadUtil;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public final class Base64Uploader {

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

		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

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

		String savePath = (String) conf.get("savePath");
		String filename = (String) conf.get("filename");

		savePath = PathFormat.parse(savePath, filename);

		SysConfigService sysConfigService = SpringUtil.getBean(SysConfigService.class);
		JSONObject object = sysConfigService.getJson("UploadFile");
		UploadUtil.init(object.getString("uploadPath"), object.getString("baseUrl"));

		StringBuilder uPath = new StringBuilder();
		uPath.append(UploadUtil.getUploadPath(savePath)).append(suffix);

		State storageState = StorageManager.saveBinaryFile(data, uPath.toString());

		if (storageState.isSuccess()) {
			StringBuilder new_file_url = new StringBuilder();
			new_file_url.append(UploadUtil.getBaseUrl(request, savePath)).append(suffix);

			storageState.putInfo("url", new_file_url.toString());
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}

		return storageState;
	}

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

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