/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.nir.nmail.spring.controllers;

import hu.nir.nmail.ejb.entity.NmailUser;
import hu.nir.nmail.services.GetSettingsService;
import hu.nir.nmail.services.ImportService;
import hu.nir.nmail.spring.beans.FileBean;
import hu.nir.nmail.utils.NmailUtility;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

/**
 *
 * @author attila
 */
public class ImportController extends SimpleFormController {
    private ImportService importService;
    private GetSettingsService getSettingsService;
    private String logoutView;
    private Logger log = Logger.getLogger(ImportController.class.getName());
    
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) {
        HttpSession session = request.getSession();
        NmailUser nmailUser = (NmailUser) session.getAttribute("nmailUser");
        FileBean fileBean = (FileBean) command;
        MultipartFile file = fileBean.getFile();
        ApplicationContext applicationContext = getApplicationContext();
        Locale locale = request.getLocale();
        
        Map<String,Object> model1 = importService.processCommand(nmailUser, file, applicationContext, locale);
        Map<String, Object> model2 = getSettingsService.processCommand(nmailUser);
        Map model = NmailUtility.mergeMaps(model1, model2);
        
        if (model.isEmpty()) {
            return new ModelAndView(getLogoutView());
        }
        
        return new ModelAndView(getSuccessView(), model);
    }

    public ImportService getImportService() {
        return importService;
    }

    public void setImportService(ImportService importService) {
        this.importService = importService;
    }

    public String getLogoutView() {
        return logoutView;
    }

    public void setLogoutView(String logoutView) {
        this.logoutView = logoutView;
    }

    public GetSettingsService getGetSettingsService() {
        return getSettingsService;
    }

    public void setGetSettingsService(GetSettingsService getSettingsService) {
        this.getSettingsService = getSettingsService;
    }
    
}
