package com.wisedu.mooc.app.upload.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.multipart.commons.CommonsMultipartFile;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.core.exception.CoeusBaseException;
import com.wisedu.coeus.core.exception.CoeusCoreException;
import com.wisedu.coeus.util.json.JSONObject;
import com.wisedu.mooc.app.upload.exception.UploadException;
import com.wisedu.mooc.app.upload.service.UploadFactory;
import com.wisedu.mooc.app.upload.service.UploadService;
import com.wisedu.mooc.app.upload.vo.UploadVo;

/**
 * 文件上传Controller
 * @author 01115035
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
	
	
	/**
	 * 文件上传处理
	 * 
	 * @param myfile   上传文件
	 * @param resType  上传文件类型
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/file/{resType}", method = RequestMethod.POST)
    public void upload(@RequestParam("Filedata") CommonsMultipartFile myfile,
                       @PathVariable String resType, HttpServletResponse response, HttpServletRequest request)
            throws IOException {
		
		//得到上传文件名称
        String fileName = myfile.getOriginalFilename();
        
        UploadVo uploadVo = null;
        try {
            // 得到处理的实力对象
            UploadService uploadService = UploadFactory.getInstance(resType);

            // 得到文件扩展名
            String fileExt = uploadService.getFileExt(fileName);
            // 扩展名是否允许上传
            boolean fileExtValid = uploadService.isFileExtValid(fileExt);
            if (!fileExtValid) {
                throw new UploadException(UploadException.UPLOAD_FILE_INVALID, null, "upload.file.invalid");
            }
            // 保存文件
            uploadVo = uploadService.saveFile(myfile.getInputStream(), fileName);
            uploadVo.setResultStatus(uploadVo.getResultStatus() == 0 ? 0 : 1);
        } catch (CoeusCoreException cce) {
            uploadVo = new UploadVo();
            uploadVo.setErrorCode(cce.getErrorCode());
            uploadVo.setErrorMag(cce.getErrorMessage());
            uploadVo.setResultStatus(ConstantStatic.INT_0);
        } catch (CoeusBaseException cbe) {
            uploadVo = new UploadVo();
            uploadVo.setErrorCode(cbe.getErrorCode());
            uploadVo.setErrorMag(cbe.getErrorMessage());
            uploadVo.setResultStatus(ConstantStatic.INT_0);
        }
        response.getWriter().print(JSONObject.toJSONString(uploadVo));
    }
	
}
