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

import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;
import it.mice.voila.runtime.util.UserMessages;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


public final class FlashMap {
	
	public static final String FLASH_MAP_ATTRIBUTE = FlashMap.class.getName();
	public static final String MESSAGE_KEY = "message";
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getCurrent() {
		HttpServletRequest request = SpringMvcUtil.getRequest(); 
		Map<String, Object> flash = (Map<String, Object>) request.getAttribute(FLASH_MAP_ATTRIBUTE);
		if (flash == null) {
			flash = new HashMap<String, Object>();
			request.setAttribute(FLASH_MAP_ATTRIBUTE, flash);
		}
		return flash;
	}
	
	private FlashMap() {
	}

	public static void put(String key, Object value) {
		getCurrent().put(key, value);
	}

	public static Object get(String key) {
		return getCurrent().get(key);
	}

	public static UserMessages getMessages() {
		Map<String, Object> flash = getCurrent();
		UserMessages result = (UserMessages)flash.get(MESSAGE_KEY);
		if (result == null) {
			result = new UserMessages();
			flash.put(MESSAGE_KEY, result);
			SpringMvcUtil.getRequest().setAttribute(MESSAGE_KEY, result);
		}
		return result;
	}
	
	public static void recycleIntoSession() {
		SpringMvcUtil.getSession().setAttribute(FLASH_MAP_ATTRIBUTE, getCurrent());
	}
}