<?php

class Xoonips_DataTypeFactory {

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

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

		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';
			}else if (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;
			}
			$dataType = new $className;
			$dataTypeId = $row['data_type_id'];
			$dataType->setId($dataTypeId);
			$dataType->setName($row['name']);
			$dataType->setModule($c);
			$dataType->setTrustDirname($trustDirname);
			$this->dataTypeInstances[$dataTypeId] = $dataType;
		}
	}

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

		return self::$instance;
	}

	public function getDataType($id) {
		return $this->dataTypeInstances[$id];
	}
}

