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

import it.mice.voila.runtime.entity.Entity;
import it.mice.voila.runtime.service.EntityService;
import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;

import java.util.Collection;

/**
 * Abstract list handler to get all results useful for populating combo boxes.
 * @author zzy9v4
 */
public abstract class AbstractListHandler {
	protected <T extends Entity> Collection<T> getList(EntityService<T> service) {
		return getList(service, false);
	}

	@SuppressWarnings("unchecked")
	protected <T extends Entity> Collection<T> getList(EntityService<T> service, boolean cacheable) {
		String attrId = service.getClass().getName() + ".findAll";
		Collection<T> cachedResult = (Collection<T>)SpringMvcUtil.getRequest().getAttribute(attrId);
		if (cachedResult == null) {
			try {
				cachedResult = service.listAll(cacheable);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			SpringMvcUtil.getRequest().setAttribute(attrId, cachedResult);
		}
		return cachedResult;
	}

}
