package it.mice.voila.runtime.springmvc.controller;

import it.mice.voila.runtime.security.AbstractFilterSecurityInterceptorPostProcessor;
import it.mice.voila.runtime.springmvc.form.LoginForm;
import it.mice.voila.runtime.springmvc.taglibs.MenuTag;
import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Default spring mvc controller for the user login to spring security.
 * The controller maps the default request to /login. Please extends this class to change its behaviour.
 */
@Controller
@RequestMapping("/manage/security")
public class ReloadSecurityController extends DefaultFormController<LoginForm> {
	private static final String INIT = "init";

	private static final String PUBLISH = "/publish";

	/**
	 * Default logger.
	 */
	private static Log logger = LogFactory.getLog(ReloadSecurityController.class);

	@Autowired(required=false)
	private AbstractFilterSecurityInterceptorPostProcessor filterSecurityInterceptorPostProcessor;

	public AbstractFilterSecurityInterceptorPostProcessor getFilterSecurityInterceptorPostProcessor() {
		return filterSecurityInterceptorPostProcessor;
	}

	public void setFilterSecurityInterceptorPostProcessor(
			AbstractFilterSecurityInterceptorPostProcessor filterSecurityInterceptorPostProcessor) {
		this.filterSecurityInterceptorPostProcessor = filterSecurityInterceptorPostProcessor;
	}

	/**
	 * Default action activated when the security/refresh was activated by menu.
	 * @param model the current spring mvc model
	 * @return the next tiles view; normally the login page.
	 */
	@RequestMapping(value = INIT, method=RequestMethod.GET)
	public String initAction(Model model) {
		return finalizeModelAndView("refreshSecurityPage", model);
	}

	/**
	 * Ricarica le informazioni sulla sicurezza dal db in memoria.
	 * @param model spring mvc model
	 * @return redirect to the refresh security page.
	 */
	@RequestMapping(value = PUBLISH, method = RequestMethod.POST)
	public String reloadSecurity(Model model) {
		if (logger.isInfoEnabled()) {
			logger.info("Reloading security configuration files from data base");
		}
		getFilterSecurityInterceptorPostProcessor().reloadInformation();
		if (logger.isInfoEnabled()) {
			logger.info("Reloading complete !");
		}
		SpringMvcUtil.cleanupSessionAttrsStartingWith(MenuTag.SAVED_MENU_DEFINITION);

		addInfoMessage("message.securityReloadComplete");
		return redirectTo(INIT);
	}
}
