package com.persagy.framework.web.controller.entrance;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Map;

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

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.persagy.core.component.JsonObjectMapper;
import com.persagy.core.constant.EMSConstant.Result;
import com.persagy.core.dto.interpreter.InterfaceResult;
import com.persagy.core.service.BusinessService;
import com.persagy.core.utils.CommonUtils;
import com.persagy.framework.util.CommonToolUtils;
import com.persagy.functions.weather.constant.Const;
import com.persagy.functions.weather.constant.ConstBusinessStatic;
import com.persagy.functions.weather.constant.WeatherConstant;
import com.persagy.functions.weather.thread.RequestIpStatisticThread;

@Scope("prototype")
@Controller("entranceController")
@RequestMapping("/entrance")
public class EntranceController {
	@Resource(name = "objectMapper")
	protected JsonObjectMapper objectMapper;

	private static final Logger log = Logger.getLogger(EntranceController.class);

	public static final String HANDLE_TYPE = "handleType";
	public static final String JSON_STRING = "jsonString";

	@Resource
	protected ApplicationContext context;

	@RequestMapping(value = "/unifier/{" + HANDLE_TYPE + "}")
	@ResponseBody
	public InterfaceResult unifier(@PathVariable(HANDLE_TYPE) String handleType,
			@RequestParam(value = JSON_STRING) String jsonString, HttpServletRequest request) throws Exception {

		String ip = CommonToolUtils.getIpAddr(request);
		ConstBusinessStatic.add(ip, handleType);
		RequestIpStatisticThread.addupdateIpApiEndDateMap(ip, handleType);
		
		Long start = System.currentTimeMillis();

		BusinessService businessService = (BusinessService) context.getBean(handleType);
		InterfaceResult interfaceResult = CommonUtils.createInterfaceResult();
		try {
			jsonString = URLDecoder.decode(jsonString, "UTF-8");
			businessService.handle(jsonString, interfaceResult.getContent());
			interfaceResult.setResult(Result.SUCCESS);
		} catch (Exception e) {
			interfaceResult.setResult(Result.FAILURE);
			interfaceResult.setReason(e.getMessage());
		    interfaceResult.getContent().clear();
		    log.error("Request Error! requesterIp="+ip+" API=" + handleType + ", Param=" + jsonString + ", Msg=" + e.getMessage(), e);
		}

		long end = System.currentTimeMillis();
	    long timeInterval = (end - start.longValue()) / 1000L;
	    if (timeInterval > 3L) {
	    	log.warn("TimeCost Warning! requesterIp=" +ip+ timeInterval + "s, API=" + handleType + ", Param=" + jsonString);
	    }
	    return interfaceResult;
	}
	
	@RequestMapping(value = "/unifierJson/{" + HANDLE_TYPE + "}")
	@ResponseBody
	public InterfaceResult unifierJson(@PathVariable(HANDLE_TYPE) String handleType,
			@RequestBody Map<String, Object> param, HttpServletRequest request) throws Exception {
		String ip = CommonToolUtils.getIpAddr(request);
		ConstBusinessStatic.add(ip, handleType);
		RequestIpStatisticThread.addupdateIpApiEndDateMap(ip, handleType);
		
		Long start = System.currentTimeMillis();

		BusinessService businessService = (BusinessService) context.getBean(handleType);
		InterfaceResult interfaceResult = CommonUtils.createInterfaceResult();
		
		String jsonString = objectMapper.writeValueAsString(param);
		try {
			jsonString = URLDecoder.decode(jsonString, "UTF-8");
			businessService.handle(jsonString, interfaceResult.getContent());
			interfaceResult.setResult(Result.SUCCESS);
		} catch (Exception e) {
			interfaceResult.setResult(Result.FAILURE);
			interfaceResult.setReason(e.getMessage());
		    interfaceResult.getContent().clear();
		    log.error("Request Error! requesterIp="+ip+" API=" + handleType + ", Param=" + jsonString + ", Msg=" + e.getMessage(), e);
		}

		long end = System.currentTimeMillis();
	    long timeInterval = (end - start.longValue()) / 1000L;
	    if (timeInterval > 3L) {
	    	log.warn("TimeCost Warning! requesterIp=" +ip+ timeInterval + "s, API=" + handleType + ", Param=" + jsonString);
	    }
	    return interfaceResult;
	}
	
	@RequestMapping(value = "/download/icon/{param}")
	public void iconDownload(@PathVariable("param") String param, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String ip = CommonToolUtils.getIpAddr(request);
		ConstBusinessStatic.add(ip, "download-icon");
		RequestIpStatisticThread.addupdateIpApiEndDateMap(ip, "download-icon");
		
		String weatherCode = "", theme = "", size = "";
		if(param != null) {
			if(param.contains("-")) {
				String[] paramArray = param.split("-");
				weatherCode = paramArray[0];
				if(paramArray.length>1) {
					theme = paramArray[1];
				}
				if(paramArray.length>2) {
					size = paramArray[2];
				}
			}else {
				weatherCode = param;
			}
		}
		
		if(WeatherConstant.getStandCodeDesc().keySet().contains(weatherCode)) {
			if(null == theme || !Const.iconTheme.contains(theme)) {
				theme = Const.iconTheme.get(0);
			}
			size = size == null ? "" : size;
			if(!Const.iconSize.keySet().contains(size)) {
				size = Const.iconSize.lastEntry().getValue();
			}else {
				size = Const.iconSize.get(size);
			}
			
			String fileName = weatherCode + "@" + size + "x.png";
			String filePath = "/static/icon/" + theme + "/" + fileName;
			
			InputStream in = this.getClass().getResourceAsStream(filePath);
			
			byte[] body = null;
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			if(null != in) {
			    byte[] buffer = new byte[4096];
			    int n = 0;
			    while (-1 != (n = in.read(buffer))) {
			        output.write(buffer, 0, n);
			    }
			    body = output.toByteArray();
			    in.close();
			    output.close();
			}

			response.setContentType("image/png");
			response.getOutputStream().write(body);
			// 设置浏览器访问下载
//			response.addHeader("Content-Disposition", "attachment;filename="+fileName);
		}
	}
}
