package com.apobates.forum.trident.controller;

import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.apobates.forum.trident.fileupload.ImageStorageExecutor;
import com.apobates.forum.utils.fileupload.ckeditor.CKEditorHightHandler;
import com.apobates.forum.utils.fileupload.fileinput.BootStrapFileInputResponse;

/**
 * 上传控制器, 若图片改用bucket模块负责此类无用
 * 
 * @author xiaofanku@live.cn
 * @since 20170515
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
	@Autowired
	private ImageStorageExecutor imageStorageExecutor;
	private final static Logger logger = LoggerFactory.getLogger(UploadController.class);

	// CK4:V4.11.4[Active][LocalStorage|本地存储]
	@RequestMapping(value = "/ckeditor", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String ckeditorUploadAction(@RequestParam("upload") MultipartFile file, @RequestParam("type") final String fileType) {
		Optional<String> data;
		try{
			data = imageStorageExecutor.store(file);
		}catch(Exception e){
			data = Optional.empty();
		}
		if(!data.isPresent()){
			return CKEditorHightHandler.buildCkeditorResponse(false, "上传失败");
		}
		String responsebody = data.get();
		return CKEditorHightHandler.buildCkeditorResponse(true, "上传成功", getFileName(responsebody), responsebody);
	}
	
	//获得图片地址的文件名
	private String getFileName(String imageURL){
		return imageURL.substring(imageURL.lastIndexOf("/") + 1);
	}
	
	@RequestMapping(value = "/fileinput", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String bootFileinputUploadAction(@RequestParam("file") MultipartFile file, @RequestParam("id")String idString, @RequestParam("uploadToken")String token){
		Optional<String> data;
		try{
			data = imageStorageExecutor.store(file);
		}catch(Exception e){
			data = Optional.empty();
		}
		if(!data.isPresent()){
			return BootStrapFileInputResponse.error("上传失败");
		}
		String responsebody = data.get();
		return new BootStrapFileInputResponse(idString, responsebody).toJson();
	}
}
