<?php

require_once 'Search.class.php';

class Xoonips_ViewTypeFactory {

	private static $instance;
	private $viewTypeInstances = array();

	private function Xoonips_ViewTypeFactory($dirname, $trustDirname) {
		global $xoopsDB;
		// get view type data
		$sql = 'select * from ' . $xoopsDB->prefix($dirname . '_view_type');
		$result = $xoopsDB->queryF($sql);

		$search = new Xoonips_Search();

		global $xoopsTpl;
			
		while ($row = $xoopsDB->fetchArray($result)) {
			$c = $row['module'];
			$className = UCfirst($trustDirname) . '_' . $c;
			if (file_exists( XOOPS_TRUST_PATH . "/modules/$trustDirname/class/core/" . $c . '.class.php')) {
				require_once XOOPS_TRUST_PATH . "/modules/$trustDirname/class/core/" . $c . '.class.php';
			} elseif (file_exists( XOOPS_TRUST_PATH . "/libs/xoonips/class/core/" . $c . '.class.php')) {
				require_once XOOPS_TRUST_PATH . "/libs/xoonips/class/core/" . $c . '.class.php';
				$className = 'Xoonips_' . $c;
			} else {
				echo "$c is not found";
				return false;
			}
			$viewType = new $className;
			$viewTypeId = $row['view_type_id'];
			$viewType->setId($viewTypeId);
			$viewType->setName($row['name']);
			$viewType->setPreslect($row['preselect']);
			$viewType->setModule($c);
			$viewType->setMulti($row['multi']);
			$viewType->setDirname($dirname);
			$viewType->setTrustDirname($trustDirname);
			$viewType->setXoopsTpl($xoopsTpl);
			$viewType->setTemplate();
			$viewType->setSearch($search);
			$this->viewTypeInstances[$viewTypeId] = $viewType;
		}
	}

	public static function getInstance($dirname, $trustDirname) {
		if (!isset(self::$instance[$dirname])) {
			$c = __CLASS__;
			self::$instance[$dirname] = new $c($dirname, $trustDirname);
		}
		return self::$instance[$dirname];
	}

	public function getViewType($id) {
		return $this->viewTypeInstances[$id];
	}
}

