package kcg.imis.cmmn.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.Resource;

import kcg.imis.cmmn.egov.EgovResourceCloseHelper;
import kcg.imis.cmmn.egov.file.EgovFileMngUtil;
import kcg.imis.cmmn.egov.util.EgovStringUtil;
import kcg.imis.cmmn.egov.util.EgovWebUtil;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import egovframework.rte.fdl.property.EgovPropertyService;
/**
  * @FileName : FileUploadUtil.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
@Component("fileUploadUtil")
public class FileUploadUtil extends EgovFileMngUtil {
	
	/**
	 * 프로퍼티 서비스.
	 */
	@Resource(name = "propertiesService")
	protected EgovPropertyService propertyService;
	
	/** Buffer size */
	public static final int BUFFER_SIZE = 8192;

	/**
	 * 파일 분리 문자. 
	 */
	public static final String SEPERATOR = File.separator;

	/**
	 * MultipartFile을 서버에 저장한다.
	 * 
	 * @param mFile
	 *            파일 객체
	 * @param path
	 *            파일이 저장될 경로 Global Property명
	 * @return 저장된 파일명
	 * @throws Exception
	 *             기본 예외 처리
	 */
	public String uploadWithExt(final MultipartFile mFile, String path) throws Exception {
		String storePathString = ""; 
		if ("".equals(path) || path == null) {
			storePathString = propertyService.getString("Globals.fileStorePath");
		} else {
			storePathString = propertyService.getString(path);
		}

		String tmp = mFile.getOriginalFilename();

		if (tmp.lastIndexOf("\\") >= 0) {
			tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
		}

		//String ext = "." + tmp.substring(tmp.lastIndexOf(".") + 1, tmp.length()).toLowerCase();
		String ext = FilenameUtils.getExtension(tmp); 
		String saveName = EgovStringUtil.getTimeStamp() + "." + ext;
		saveName = super.makeNewFileName(storePathString, saveName);
		//saveName = saveName.substring(0, saveName.length() - 3) + ext;
		
		if (mFile.getSize() > 0) {
			InputStream is = null;
			try {
				is = mFile.getInputStream();
				saveFile(is, new File(EgovWebUtil.filePathBlackList(storePathString + saveName)));
			} finally {
				if (is != null) {
					is.close();
				}
			}
		}
		return saveName;
	}
	
	/**
	 * Stream으로부터 파일을 저장함.
	 * @param is InputStream
	 * @param file File
	 * @throws IOException
	 */
	private long saveFile(final InputStream is, final File file) throws IOException {
		// 디렉토리 생성
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}

		OutputStream os = null;
		long size = 0L;

		try {
			os = new FileOutputStream(file);

			int bytesRead = 0;
			byte[] buffer = new byte[BUFFER_SIZE];

			while ((bytesRead = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
				size += bytesRead;
				os.write(buffer, 0, bytesRead);
			}
		} finally {
			EgovResourceCloseHelper.close(os);
		}

		return size;
	}
}
