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 javax.servlet.http.HttpSession;

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 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.HashUtil;
import com.dbs.mplus.service.MPlusConfigureService;
import com.dbs.mplus.service.RememberMeCookieBaker;
import com.dbs.mplus.service.mobile.user.MPUserService;


@Controller
@RequestMapping("/mobile/withdrawal")
@ServiceMenu(menuId="withdrawal", description="탈퇴")
public class UserWithdrawalController  extends AbstractController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired 
	private MPlusConfigureService configureService; 	
	@Autowired 
	private MPUserService userService; 
	@Autowired
	private RememberMeCookieBaker cookieBaker;
	
	
	/**
	 * 탈퇴 
	 * @param request
	 * @param response
	 * @param reqMap
	 * @return
	 * @throws MobileControllerException
	 */
	@RequestMapping(value = "/withdrawal.json", method = RequestMethod.POST)
	public Map<String, Object> withdrawalUser(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()); 
		} 
		
		
		// 환자변호 
		final String userId = (String) reqMap.get("userId"); 
		// 비번 
		final String plainPassword = (String) reqMap.get("passWord"); 

		// 유효성 확인 
		if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(plainPassword)) {
			throw new MobileControllerException("mplus.auth.unauthenticated", "인증되지 않은 사용자입니다"); 
		}
		
		// 비번확인 
		final HashUtil hashUtils = new HashUtil(this.configureService.getHashSalt()); 
		final boolean checkedPwd = this.userService.checkUserPWD(userId, hashUtils.sha256(plainPassword)); 
		if(!checkedPwd) { 
			throw new MobileControllerException("admin.auth.checkaccount", "비밀번호를 다시 확인하세요"); 
		}
		
		final Map<String, Object> resultMap = new HashMap<String, Object>(); 
		
		// 삭제 
		try { 
			this.userService.removeUser(userId);
			resultMap.put("result", "success"); 
			
			try { 
				// 회원정보 삭제 성공시, 자동로그인 쿠키 삭제 
				this.cookieBaker.remove(request, response);
			} 
			catch(final Exception ex) {
				this.logger.error("자동로그인 쿠키 삭제 실패. 계속진행함.", ex);
				// 쿠키삭제실패해도, 이후처리 계속 가능함
			}
			
			//그리고 세션 날림
			final HttpSession session = request.getSession(false);
			if (session != null) {
				this.logger.debug("로그아웃을 위해 세션 초기화 처리");
				session.invalidate();
			}
		}
		catch(final Exception ex) {
			if(this.logger.isDebugEnabled()) {
				this.logger.debug("예외발생", ex); 
			}
			
			resultMap.put("result", "fail"); 
		}
	
		return resultMap; 
	}
}
