<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_MODULE_PATH . "/legacyRender/admin/class/LegacyTheme.class.php";
require_once XOOPS_MODULE_PATH . "/legacyRender/admin/forms/ThemeSelectForm.class.php";

/**
 * This action shows the list of selectable themes to user.
 */
class LegacyRender_ThemeListAction extends LegacyRender_Action
{
	var $mThemes = null;
	var $mObjectHandler = null;
	var $mActionForm=null;

	function prepare(&$controller, &$xoopsUser)
	{
		$this->_setupObject();
		$this->_setupActionForm();
	}
	
	function _setupObject()
	{
		if ($this->mThemes == null) {
			$this->mObjectHandler =& xoops_getmodulehandler('theme');
			$this->mObjectHandler->updateThemeList();

			$this->mThemes =& $this->mObjectHandler->getObjects();
		}
	}

	function _setupActionForm()
	{
		if ($this->mActionForm == null) {
			$this->mActionForm = new ThemeSelectForm();
			$this->mActionForm->prepare();
		}
	}
	
	function getDefaultView(&$controller, &$xoopsUser)
	{
		$this->mActionForm->load($this->mThemes);

		return LEGACYRENDER_FRAME_VIEW_INDEX;
	}
	
	function execute(&$controller, &$xoopsUser)
	{
		$this->mActionForm->fetch();
		$this->mActionForm->validate();
		
		$this->mActionForm->update($this->mThemes);

		if ($this->mActionForm->hasError()) {
			return $this->getDefaultView($controller, $xoopsUser);
		}

		//
		// save
		//
		foreach ($this->mThemes as $theme) {
			$this->mObjectHandler->insert($theme);
		}
		

		//
		// save selected theme.
		//
		$themeName = $this->mActionForm->getChooseTheme();
		
		if ($themeName != null) {
			$configHandler =& xoops_gethandler('config');

			$criteria =& new CriteriaCompo();
			$criteria->add(new Criteria('conf_name', 'theme_set'));
			$criteria->add(new Criteria('conf_catid', XOOPS_CONF));
			
			$configs =& $configHandler->getConfigs($criteria);

			$configs[0]->setVar('conf_value', $themeName);
			if ($configHandler->insertConfig($configs[0])) {
				$controller->mRoot->setThemeName($this->mActionForm->getChooseTheme());
			}
		}

		return $this->getDefaultView($controller, $xoopsUser);
	}
	
	function executeViewIndex(&$controller, &$xoopsUser, &$render)
	{
		foreach (array_keys($this->mThemes) as $name) {
			$this->mThemes[$name]->loadPackage();
		}
		
		$render->setTemplateName("theme_list.html");
		$render->setAttribute("themes", $this->mThemes);
		$render->setAttribute("actionForm", $this->mActionForm);
		$render->setAttribute("currentThemeName", $controller->mRoot->getThemeName());
	}
}

?>