package egovframework.rex.util.web.muilt.controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import egovframework.rex.util.fileupload.muilt.service.FileInfoVO;

/**
 * @file Name : GenericFileUploadController.java
 * @Description : GenericFileUploadController
 * @Modification Information
 * @
 * @  수정일         수정자                   수정내용
 * @ -------    --------    ---------------------------
 * @ 2009.03.05      이동도          최초 생성
 *
 *  @author 실행환경 개발팀 이동도
 *  @since 2009.03.05
 *  @version 1.0
 *  @see
 *  
 *  Copyright (C) 2009 by MOPAS  All right reserved.
 */

@Controller("genericFileUploadController")
public class GenericFileUploadController {

	@Resource(name = "multipartResolver")
	CommonsMultipartResolver mailmultipartResolver;

	@Resource(name = "fileUploadProperties")
	Properties fileUploadProperties;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/upload/genericMulti.do")
	public String multipartProcess(final HttpServletRequest request, Model model)
			throws Exception {

		final long startTime = System.nanoTime();

		/*
		 * validate request type
		 */
		Assert.state(request instanceof MultipartHttpServletRequest,
				"request !instanceof MultipartHttpServletRequest");
		final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

		/*
		 * validate text input
		 */
		Assert.state(request.getParameter("type").equals("genericFileMulti"),
				"type != genericFileMulti");

		/*
		 * extract files
		 */
		final Map<String, MultipartFile> files = multiRequest.getFileMap();
		Assert.notNull(files, "files is null");
		Assert.state(files.size() > 0, "0 files exist");

		/*
		 * process files
		 */
		String uploadPath = fileUploadProperties
				.getProperty("file.upload.path");
		File saveFolder = new File(uploadPath);

		// 디렉토리 생성 (보안 취약점 개선) 2009.04.02
		boolean isDir = false;

		if (!saveFolder.exists() || saveFolder.isFile()) {
			saveFolder.mkdirs();
		}
			
		if (!isDir) {

			Iterator<Entry<String, MultipartFile>> itr = files.entrySet()
					.iterator();
			MultipartFile file;
			List fileInfoList = new ArrayList();
			String filePath;

			while (itr.hasNext()) {
				Entry<String, MultipartFile> entry = itr.next();
				System.out.println("[" + entry.getKey() + "]");

				file = entry.getValue();
				if (!"".equals(file.getOriginalFilename())) {
					filePath = uploadPath + "\\" + file.getOriginalFilename();
					file.transferTo(new File(filePath));

					FileInfoVO fileInfoVO = new FileInfoVO();
					fileInfoVO.setFilePath(filePath);
					fileInfoVO.setFileName(file.getOriginalFilename());
					fileInfoVO.setFileSize(file.getSize());
					fileInfoList.add(fileInfoVO);
				}
			}

			model.addAttribute("fileInfoList", fileInfoList);
			model.addAttribute("uploadPath", uploadPath);

			// 여기서는 DB에 파일관련 정보를 저장하지 않고 단순히 success 페이지로 포워딩 하여 재확인 가능토록 함
			final long estimatedTime = System.nanoTime() - startTime;
			System.out.println(estimatedTime + " " + getClass().getSimpleName());

		}
		return "success";

	}
}