/*
 * 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.resource;

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.Resource;
import nuts.aems.model.dao.ResourceDAO;
import nuts.aems.model.example.ResourceExample;
import nuts.exts.xwork2.util.LocalizedTextUtils;

/**
 */
public class ResourceLoadAction 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().getDatabaseResourceLoader() != null) {
			if (processing) {
				addActionMessage(getText(RC.MESSAGE_PROCESSING));
			}
			else {
				try {
					processing = true;

					removeApplicationMessage(AC.RESOURCE_RELOAD);
					removeApplicationError(AC.RESOURCE_RELOAD);
	
					loadResources();
					
					addActionMessage(getText(RC.MESSAGE_PROCESSED));
				}
				catch (Throwable e) {
					addApplicationError(AC.RESOURCE_RELOAD, 
							getText(RC.ERROR_RESOURCE_RELOAD, new String[] { e.getMessage() }));
				}
				finally {
					processing = false;
				}
			}
		}
		return SUCCESS;
	}

	/**
	 * @throws Exception if an error occurs
	 */
	private void loadResources() throws Exception {
		log.info("Loading database resources ...");
		
		ResourceDAO tDao = new ResourceDAO(getDataAccessSession());
		ResourceExample tExp = tDao.createExample();
		tExp.invalid().isFalse();
		
		List<Resource> list = tDao.selectByExample(tExp);
		
		WebApplet.get().getDatabaseResourceLoader().loadResources(list);

		LocalizedTextUtils.clearResourceBundlesCache();

		WebApplet.get().onResourceLoaded();
		
		MemCacheInterceptor.setCacheReloadTime(AC.RESOURCE_RELOAD, reset);
	}
}
