package kcg.faics.tg.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import kcg.faics.cmmn.bbs.BaseBbsService;
import kcg.faics.cmmn.egov.file.EgovFileMngUtil;
import kcg.faics.cmmn.egov.vo.FileVO;
import kcg.faics.tg.vo.FerrySearchVO;
import kcg.faics.tg.vo.FerryVO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;

/**
 * 국제여객선 관련 비지니스로직.
 * 
 * @author kimnomin
 *
 */
@Service("ferryService")
public class FerryServiceImpl extends EgovAbstractServiceImpl implements
		BaseBbsService<FerrySearchVO, FerryVO> {
	
	/**
	 * property 파일에서 읽은 저장 경로 키워드. 
	 */
	public static final String FILE_PATH_KEYWORD = "Target.ferry.fileStorePath";
	
    /**
	 * 전자정부프레임워크에서 제공되는 파일 업로드 처리 관련 Utility.
	 **/
	@Resource(name = "EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;	
	
	/**
	 * 국제여객선 Mapper 클래스.
	 */
	@Resource(name = "ferryMapper")
	private FerryMapper ferryMapper;

	/**
	 * Place별 다음에 사용할 DS_NO를 반환한다.
	 * 
	 * @param ferryVO
	 *            국제여객선 VO
	 * @return SER_NO 최대 값+1
	 * @throws Exception
	 *             기본 예외 처리
	 */
	private int selectNextSerNo(final FerryVO ferryVO) throws Exception {
		int result = 1;
		try {
			result = ferryMapper.selectMaxSerNo(ferryVO) + 1; 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result; 
	}
	
	@Override
	public FerryVO select(final FerryVO dataVO) throws Exception {
		return ferryMapper.select(dataVO);
	}

	@Override
	public List<FerryVO> selectListAll(final FerrySearchVO searchVO)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<FerryVO> selectList(final FerrySearchVO searchVO) throws Exception {
		return ferryMapper.selectList(searchVO);
	}

	@Override
	public int selectListCnt(final FerrySearchVO searchVO) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int selectTotalCnt(final FerrySearchVO searchVO) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public HashMap<String, Object> insert(final FerryVO dataVO,
			final Map<String, MultipartFile> fileMap) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		int no = selectNextSerNo(dataVO);
		if (no > 0) {
			dataVO.setSerNo(no);
			
			List<FileVO> fileList = fileUtil.parseFileInf(fileMap, null, 0, "", FILE_PATH_KEYWORD);
			for (FileVO fileVO : fileList) {
				if ("imgFileObj".equalsIgnoreCase(fileVO.getFileSn())) {
					dataVO.setImgFile(fileVO.getStreFileNm());
				}
			}
			
			map.put("result", ferryMapper.insert(dataVO));
		} else {
			map.put("result", 0);
		}
		
		return map;
	}

	/**
	 * Update시 파일삭제 대상을 판별한다.
	 * 
	 * @param fileMap 파일 Map 객체
	 * @param fileMapKey 파일 Map 객체에서 추출할 key
	 * @param deleteFileList 삭제대상 목록
	 * @param deleteFileListKey 삭제대상 목록에서 추출할 문자열
	 * @return 파일삭제여부
	 */
	private boolean isRemoveTarget(final Map<String, MultipartFile> fileMap,
			final String fileMapKey, final List<String> deleteFileList,
			final String deleteFileListKey) {
		boolean isRemoveTarget = false;
		
		if (deleteFileList.contains(deleteFileListKey)
				|| (fileMap.containsKey(fileMapKey) && fileMap.get(fileMapKey).getSize() > 0)) {
			isRemoveTarget = true;
		}
		
		return isRemoveTarget;
	}
	
	@Override
	public HashMap<String, Object> update(final FerryVO dataVO,
			final Map<String, MultipartFile> fileMap, final String[] deleteFiles)
			throws Exception {
		FerryVO vo = select(dataVO);
		dataVO.setImgFile(vo.getImgFile());
		
		List<String> deleteFileList = new ArrayList<String>();
		if (deleteFiles != null) {
			deleteFileList = Arrays.asList(deleteFiles);
		}
		if (isRemoveTarget(fileMap, "imgFileObj", deleteFileList, "imgFile")) {
			fileUtil.deleteFile(vo.getImgFile(), FILE_PATH_KEYWORD);
			dataVO.setImgFile("");
		}
		
		List<FileVO> fileList = fileUtil.parseFileInf(fileMap, null, 0, "", FILE_PATH_KEYWORD);
		for (FileVO fileVO : fileList) {
			if ("imgFileObj".equalsIgnoreCase(fileVO.getFileSn())) {
				dataVO.setImgFile(fileVO.getStreFileNm());
			}
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("result", ferryMapper.update(dataVO));
		
		return map;
	}

	@Override
	public HashMap<String, Object> delete(final FerryVO dataVO) throws Exception {
		FerryVO vo = select(dataVO);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("result", ferryMapper.delete(dataVO));
		
		if (StringUtils.isNotBlank(vo.getImgFile())) {
			fileUtil.deleteFile(vo.getImgFile(), FILE_PATH_KEYWORD);
		}
		
		return map;
	}
}
