/*
 * 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.POP3Service;
import hu.nir.nmail.utils.NmailUtility;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

/**
 *
 * @author attila
 */
public class POP3Controller extends SimpleFormController {
    private String logoutView;
    private POP3Service pop3Service;
    private GetSettingsService getSettingsService;

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        HttpSession session = request.getSession();
        NmailUser nmailUser = (NmailUser) session.getAttribute("nmailUser");
        Map<String, Object> model1 = pop3Service.processCommand(nmailUser, command);
        Map<String, Object> model2 = getSettingsService.processCommand(nmailUser);
        Map<String, Object> model = NmailUtility.mergeMaps(model1, model2);
        
        if (model == null) {
            return new ModelAndView(getLogoutView());
        }
        
        return new ModelAndView(getSuccessView(), model);
    }
    
    @Override
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors, Map controlModel) throws Exception {
        if (controlModel == null || controlModel.isEmpty()) {
            HttpSession session = request.getSession();
            NmailUser nmailUser = (NmailUser) session.getAttribute("nmailUser");
            controlModel = new HashMap();
            controlModel = getSettingsService.processCommand(nmailUser);
            if (controlModel == null) {
                setFormView(logoutView);
            }
            controlModel = NmailUtility.mergeMaps(controlModel, errors.getModel());
        }
        return super.showForm(request, response, errors, controlModel);
    }

    public String getLogoutView() {
        return logoutView;
    }

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

    public POP3Service getPop3Service() {
        return pop3Service;
    }

    public void setPop3Service(POP3Service pop3Service) {
        this.pop3Service = pop3Service;
    }

    public GetSettingsService getGetSettingsService() {
        return getSettingsService;
    }

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