package com.dbs.mplus.controller.mobile;

import java.util.List;
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.util.StringUtils;
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 com.dbs.mplus.exception.mobile.ApiCallException;
import com.dbs.mplus.exception.mobile.MobileControllerException;
import com.dbs.mplus.framework.exception.MPlusServiceException;
import com.dbs.mplus.framework.service.menu.ServiceMenu;
import com.dbs.mplus.framework.template.AbstractController;
import com.dbs.mplus.framework.util.ResponseUtil;
import com.dbs.mplus.service.api.MPlusApi;
import com.dbs.mplus.service.api.MPlusApiCallService;

@Controller
@RequestMapping("/mobile/pushToken")
@ServiceMenu(menuId="pushToken", description="push token 관리")
public class TokenController extends AbstractController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private MPlusApiCallService apiCallService; 
	
	
	// 토큰을 가지고 있는 환자목록 반환 
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getList.json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object>  getList(HttpServletRequest request, HttpServletResponse response, 
			@RequestBody Map<String, Object> reqMap) throws MobileControllerException {
		
		// 접근권한 및 파라미터 정리 
		try { 
			reqMap = super.isAccessableMenu(this.getClass(), request, reqMap); 
		}
		catch(MPlusServiceException ex) { 
			throw new MobileControllerException(ex.getCode(), ex.getMessage()); 
		}
		
		
		List<Map<String, Object>> resultList = null; 
		
		// 기능호출 
		try { 
			resultList = (List<Map<String, Object>>) this.apiCallService.execute(MPlusApi.USER_USERINFO_GETDEVICETOKENUSERLIST, reqMap); 
		}
		catch(ApiCallException ex) { 
			if(this.logger.isDebugEnabled()) {
				this.logger.debug("예외발생", ex); 
			}
			
			throw new MobileControllerException("mplus.error.if.system", "시스템 호출 오류가 발생했습니다 (IF)");
		}	

		
		// 결과가 없으면 빈거대로 반환 
		if(resultList == null || resultList.isEmpty()) {
			return ResponseUtil.wrapEmptyResultMap(); 
		}
		
		// 화면에서 보낸 토큰 
		final String currentUserToken = (String) reqMap.get("deviceTokenId"); 
		final String currentUserTokenKey = "currentDevice"; 

		// 현재 사용자 토큰이 없는경우, push수신거부라든가 웹 화면이라든가 
		if(StringUtils.isEmpty(currentUserToken)) {
			// 무조건 현재장비가 아닌걸로 
			for(Map<String, Object> map  : resultList) { 
				map.put(currentUserTokenKey, "N"); 
			}
		}
		// 비교 필요 
		else {
			for(Map<String, Object> map  : resultList) { 
				String token = (String) map.get("deviceTokenId"); 
				if(currentUserToken.equals(token)) {
					map.put(currentUserTokenKey, "Y"); 
				}
				else {
					map.put(currentUserTokenKey, "N"); 
				}
			}
		}
		
		return ResponseUtil.wrapResultMap(resultList); 
	}
	
	// 삭제 
	@RequestMapping(value = "/remove.json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object>  remove(HttpServletRequest request, HttpServletResponse response, 
			@RequestBody Map<String, Object> reqMap) throws MobileControllerException {
		
		// 접근권한 및 파라미터 정리 
		try { 
			reqMap = super.isAccessableMenu(this.getClass(), request, reqMap); 
		}
		catch(MPlusServiceException ex) { 
			throw new MobileControllerException(ex.getCode(), ex.getMessage()); 
		}
		
		// 기능호출 
		try { 
			return this.apiCallService.call(MPlusApi.USER_USERINFO_DELETEDEVICETOKENUSER, reqMap); 
		}
		catch(ApiCallException ex) { 
			if(this.logger.isDebugEnabled()) {
				this.logger.debug("예외발생", ex); 
			}
			
			throw new MobileControllerException("mplus.error.if.system", "시스템 호출 오류가 발생했습니다 (IF)");
		}		
	}	
}
