package cn.myapps.support.tray.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.myapps.common.util.DefaultProperty;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.util.FileEncryptAndDecrypt;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller(value="TrayServiceAction")
@RequestMapping(value="/api/tray/service")
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class TrayServiceController{
	
	protected static final String ACTION_RESULT_KEY = "status";
	protected static final int ACTION_RESULT_VALUE_SUCCESS = 1;
	protected static final int ACTION_RESULT_VALUE_FAULT = 0;
	
	protected static final String ACTION_MESSAGE_KEY = "message";
	protected static final String ACTION_DATA_KEY = "data";
	
	
	protected ParamsTable params;
	
	//将会被Struts2序列化为JSON字符串的对象,用来作为控制层返回结果的容器
	protected Map<String, Object> dataMap = new HashMap<String, Object>();
	
	@Autowired  
	protected HttpServletRequest request;
	
	@Autowired  
	protected HttpServletResponse response;
	
	@Autowired
	protected HttpSession session;
	
	
	@RequestMapping(value="/download.action")
	@ResponseBody
	public void doDownload() throws Exception {
		File file = null;
		HttpServletRequest request = this.request;
		HttpServletResponse response = this.response;
		try {
			ParamsTable params = getParams();
			String path = params.getParameterAsString("path");
			String name = params.getParameterAsString("name");
			
			if(!StringUtil.isBlank(path)){
				String realPath = PropertyUtil.getPath()+File.separator+path+File.separator+name;
				file = new File(realPath);
				if(FileEncryptAndDecrypt.isEncrypt(realPath)){
					file = new File(FileEncryptAndDecrypt.encrypt(realPath));
				}
				if(!file.exists()) {
					response.setStatus(404);
					return;
				}
			setResponse(response, file);
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(500);
		}
	}
	
	private void setResponse(HttpServletResponse response, File file) throws IOException {
		OutputStream os = null;
		BufferedInputStream reader = null;
		try {
			String encoding = "utf-8";
			HttpServletRequest request = this.request;
			String agent = request.getHeader("USER-AGENT");
//			String address = file.toString();
			if(null != agent && -1 != agent.indexOf("Firefox")){
				response.setContentType("application/x-download; charset=" + encoding + "");
				response.setHeader("Content-Disposition", "attachment;filename=\"" + MimeUtility.encodeText(file.getName(), encoding, "B") + "\"");
			}else{
				response.setContentType("application/x-download; charset=" + encoding + "");
				response.setHeader("Content-Disposition", "attachment;filename=\"" + java.net.URLEncoder.encode(file.getName(), encoding) + "\"");
			}
			os = response.getOutputStream();

			reader = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[4096];
			int i = -1;
			while ((i = reader.read(buffer)) != -1) {
				os.write(buffer, 0, i);
			}
			os.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			if (os != null) {
				reader.close();
			}
			if ( reader != null) {
				reader.close();
			}
		}
	}
	
	public ParamsTable getParams() {
		if (params == null) {
			params = ParamsTable.convertHTTP(this.request);

			params.setSessionid(this.session.getId());

			if (params.getParameter("_pagelines") == null){
				params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
			}
		}
		return params;
	}
	
	public ParamsTable getParams(HttpServletRequest request) {
		if (params == null) {
			params = ParamsTable.convertHTTP(request);

			params.setSessionid(request.getSession().getId());

			if (params.getParameter("_pagelines") == null){
				params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
			}
		}
		return params;
	}
	
	
	 /**
     * Struts2序列化指定属性时，必须有该属性的getter方法
     * @return
     */
    public Map<String, Object> getDataMap() {
        return dataMap;
    }
	/**
     * 添加Action处理结果
     * @param isSuccess
     * 		是否成功处理
     * @param message
     * 		返回消息
     * @param data
     * 		返回数据
	 * @return 
     */
    public Map<String, Object> addActionResult(boolean isSuccess,String message,Object data){
    	dataMap.put(ACTION_RESULT_KEY, isSuccess?ACTION_RESULT_VALUE_SUCCESS : ACTION_RESULT_VALUE_FAULT );
    	dataMap.put(ACTION_MESSAGE_KEY, message);
    	if(data != null){
    		dataMap.put(ACTION_DATA_KEY, data);
    	}
    	return dataMap;
    }

}
