package com.eactive.eai.rms.common.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.eactive.eai.rms.common.base.BaseAnnotationController;

@Controller
public class FileUploadController extends BaseAnnotationController {

//    private static final Logger logger = Logger.getLogger(FileUploadController.class);

  
    @RequestMapping(value= "/fileupload.json",method=RequestMethod.GET)
	public String displayForm() {
		return "fileupload";
	}    
    
    @RequestMapping(value= "/fileUpload.json",method=RequestMethod.POST)
	public String upload(@ModelAttribute("uploadForm") FileForm uploadForm,
			Model map) throws Exception {
		List<MultipartFile> files = uploadForm.getFiles();

		List<String> fileNames = new ArrayList<String>();

		if (null != files && files.size() > 0) {
			for (MultipartFile multipartFile : files) {
				String fileName = multipartFile.getOriginalFilename();
				String path = uploadForm.getUploadDir() + fileName;
				File f = new File(path);
				multipartFile.transferTo(f);
				fileNames.add(fileName);
			}
		}

		map.addAttribute("files", fileNames);
		return "success";
	}  
}
