/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems.action.template;

import java.util.List;

import nuts.aems.WebApplet;
import nuts.aems.action.AbstractAction;
import nuts.aems.constant.AC;
import nuts.aems.constant.RC;
import nuts.aems.interceptor.MemCacheInterceptor;
import nuts.aems.model.bean.Template;
import nuts.aems.model.dao.TemplateDAO;
import nuts.aems.model.example.TemplateExample;

/**
 */
public class TemplateLoadAction extends AbstractAction {

	private static boolean processing = false;
	
	private boolean reset = true;

	/**
	 * @return the reset
	 */
	public boolean isReset() {
		return reset;
	}

	/**
	 * @param reset the reset to set
	 */
	public void setReset(boolean reset) {
		this.reset = reset;
	}
	
	/**
	 * load
	 * @return SUCCESS
	 * @throws Exception if an error occurs
	 */
	public String load() throws Exception {
		if (WebApplet.get().getDatabaseTemplateLoader() != null) {
			if (processing) {
				addActionMessage(getText(RC.MESSAGE_PROCESSING));
			}
			else {
				try {
					processing = true;

					removeApplicationMessage(AC.TEMPLATE_RELOAD);
					removeApplicationError(AC.TEMPLATE_RELOAD);
	
					loadTemplates();
	
					addActionMessage(getText(RC.MESSAGE_PROCESSED));
				}
				catch (Throwable e) {
					addApplicationError(AC.TEMPLATE_RELOAD, 
							getText(RC.ERROR_TEMPLATE_RELOAD, new String[] { e.getMessage() }));
				}
				finally {
					processing = false;
				}
			}
		}
		return SUCCESS;
	}
	
	private void loadTemplates() throws Exception {
		TemplateDAO tDao = new TemplateDAO(getDataAccessSession());
		TemplateExample tExp = tDao.createExample();
		tExp.invalid().isFalse();
		
		List<Template> list = tDao.selectByExample(tExp);
		
		WebApplet.get().getDatabaseTemplateLoader().loadTemplates(list);
		
		MemCacheInterceptor.setCacheReloadTime(AC.TEMPLATE_RELOAD, reset);
	}
}
