package kcg.faics.member.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import kcg.faics.cmmn.file.FileResponser;
import kcg.faics.cmmn.service.CodeService;
import kcg.faics.member.UserType;
import kcg.faics.member.service.MemberService;
import kcg.faics.member.vo.MemberSearchVO;
import kcg.faics.member.vo.MemberVO;
import kcg.faics.sec.LoginUserVO;
import kcg.faics.sec.UserUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
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.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
@Controller
@RequestMapping("/member")
public class MemberController {

	@Resource(name = "memberService")
	MemberService memberService;

	@Resource(name = "propertiesService")
	private EgovPropertyService propertiesService;

	/**
	 * 코드관련 정보 인터페이스.
	 */
	@Resource(name = "codeService")
	private CodeService codeService;

	@ResponseBody
	@RequestMapping(value = "/faIdCheck.json")
	public HashMap<String, Object> checkMemberId(final MemberVO memberVO) throws Exception {
		HashMap<String, Object> result = new HashMap<String, Object>();
		memberVO.setUsertype(UserType.FA);
		MemberVO vo = memberService.select(memberVO);
		result.put("data", (vo != null) ? 1 : 0);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/changePw.json")
	public HashMap<String, Object> changePw(final MemberVO memberVO) throws Exception {
		if (StringUtils.isBlank(memberVO.getUserid())) {
			LoginUserVO user = UserUtil.getMemberInfo();
			memberVO.setUserid(user.getUserid());
			memberVO.setUsertype((user.getType() == 1) ? UserType.FA : UserType.CM);	
		}
		
		return memberService.updatePassword(memberVO);
	}
	
	public static final String FILE_PATH_KEYWORD = "Member.fileStorePath";
	
	@RequestMapping(value = "/download.do")
	public void fileResponse(final String filenm, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
			
		if (StringUtils.isNotBlank(filenm)) {
			String fileFullPath = propertiesService.getString(FILE_PATH_KEYWORD) + filenm;
			File file = new File(fileFullPath);
			if (file.exists()) {
				FileResponser.setResponse(file, filenm, request, response);
				BufferedInputStream in = null;
				try {
					in = new BufferedInputStream(new FileInputStream(file));
					FileCopyUtils.copy(in, response.getOutputStream());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		} else {
			response.setStatus(HttpStatus.NOT_FOUND.value());			
			throw new Exception();
		}
	}
	
	/**
	 * 외사경찰 목록(no paging)읇 반환한다.
	 * 
	 * @param searchVO
	 *            검색정보 객체
	 * @return 외사경찰 목록(json)
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@ResponseBody
	@RequestMapping(value = "/faListAll.json")
	public List<MemberVO> getFaListAll(final MemberSearchVO searchVO) throws Exception {
		List<MemberVO> faList = memberService.getFaListAll(searchVO);
		return faList;
	}
	
	/**
	 * 일반경찰을 삭제한다.
	 * 
	 * @param vo 사용자 VO
	 * @return (json) {result: 1 - 성공, 0 - 실패}
	 * @throws Exception 기본 예외 처리
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCmmn.json")
	public HashMap<String, Object> deleteCmmnMember(final MemberVO vo) throws Exception {
		if (UserUtil.isAdmin()) {
			return memberService.delete(vo, UserType.CM);	
		}
		return null;
	}
	
	/**
	 * 회원정보 화면을 반환한다.
	 * 
	 * @param memberVO 멤버 객체
	 * @param model 모델 객체
	 * @return 회원정보 화면
	 * @throws Exception 기본예외처리
	 */
	@RequestMapping(value = "/cmmnView.do")
	public String infoView(final MemberVO memberVO, final Model model) throws Exception {
		memberVO.setUserid(UserUtil.getMemberInfo().getUserid());
		model.addAttribute("memberVO", memberService.select(memberVO));
		return "/member/view.tiles";
	}

	/**
	 * 회원정보 수정 화면을 반환한다.
	 * 
	 * @param memberVO 멤버 객체
	 * @param model 모델 객체
	 * @return 회원정보 수정 화면
	 * @throws Exception 기본예외처리
	 */
	@RequestMapping(value = "/cmmnUpdateView.do")
	public String updateView(final MemberVO memberVO, final Model model) throws Exception {
		
		if (StringUtils.isBlank(memberVO.getUserid())) {
			return infoView(memberVO, model);
		}
		model.addAttribute("memberVO", memberService.select(memberVO));
		
		model.addAttribute("place1List", codeService.getPlace1List(false));
		model.addAttribute("positionList", codeService.getPositionList());
		return "/member/update.tiles";
	}

	/**
	 * 회원정보 수정한다.
	 * 
	 * @param memberVO 멤버 객체
	 * @param model 모델 객체
	 * @param status SessionStatus 객체
	 * @return 회원정보 화면
	 * @throws Exception 기본예외처리
	 */
	@RequestMapping(value = "/cmmnUpdate.do")
	public String update(final MemberVO memberVO, final Model model, final SessionStatus status) throws Exception {
		/* 인증된 사용자인지 확인 */
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
		if (isAuthenticated) {
			try {
				
				int result = memberService.updateCmmnMemberInfo(memberVO);
				
				status.setComplete();
				
				if (result == 1) {
					return "redirect:/member/cmmnView.do?userid=" + memberVO.getUserid();
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return "error/bizError";
	}
}
