package com.dbs.mplus.controller.mobile;

import java.util.HashMap;
import java.util.Map;

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

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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;

import com.dbs.mplus.exception.mobile.ApiCallException;
import com.dbs.mplus.exception.mobile.MobileControllerException;
import com.dbs.mplus.framework.service.MessageService;
import com.dbs.mplus.service.api.MPlusApi;
import com.dbs.mplus.service.api.MPlusApiCallService;
/**
 * 버전확인 
 * @author aple
 *
 */
@Controller
@RequestMapping("/mobile/version")
public class VersionCheckController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MPlusApiCallService apiCallService; 	
	@Autowired
	private MessageService messageService;	
	
	/**
	 * 앱이름, 플랫폼, 인증서를 조합해서 버전확인 
	 * 메뉴도 없고, 권한확인이 없는 요청임 
	 * @param request
	 * @param response
	 * @param paramMap
	 * @return
	 * @throws MobileControllerException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/appVersion.json", method = RequestMethod.POST) 
	@ResponseBody
	public Map<String, Object> checkAppVersion(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Map<String, Object> paramMap) throws MobileControllerException {

		if(this.logger.isDebugEnabled()) { 
			this.logger.debug("request : " + request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
		}
		
		Map<String, Object> map = null; 
		
		
		try { 
			// 이 메소드는 UI가 아닌 device에서 호출됨 
			map = (Map<String, Object>) this.apiCallService.execute(MPlusApi.APP_CHECKAPPNAMEVERSION, paramMap);
		}
		catch(final ApiCallException ex) { 
			// 결과가 2개 조회되는 경우 CastException이 발생할것임 
			if(this.logger.isErrorEnabled()) {
				this.logger.error("앱버전확인 API 확인필요", ex);
			}
			
			return this.getVersionCheckError(request); 
		}

		// 결과가 없는 경우에도 에러러 전달해야 함 
		if(map == null || map.isEmpty()) { 
			if(this.logger.isErrorEnabled()) {
				this.logger.error("서버에 앱 버전이 등록되어 있지 않음. 관리자 콘솔에서 등록해주세요.");
			}
			return this.getVersionCheckError(request); 
		}
	
		return map; 
	}
	
	/**
	 * 에러 메시지 만들기 
	 * @param request
	 * @return
	 */
	private Map<String, Object> getVersionCheckError(HttpServletRequest request) {
		final Map<String, Object> map = new HashMap<String, Object>(); 
		map.put("error", this.messageService.getMessage("mplus.error.no.version", request)); 
		return map; 
	}
}
