<?php
/**
 * Unit_cache_table.php - The library for handling the unit_search_cache tables.
 *
 * @author $Author: dtong $
 * @version $Id: Unit_cache_table.php,v 1.1 2010/07/30 05:38:03 dtong Exp $
 * @copyright Copyright (c) 2010, Tiller Software Co., Ltd.
*/
require_once 'memory_table.php';

class Unit_cache_table {
	private $memtab = NULL;
	private $table_name = 'unit_search_cache';
	private $update_sql = 'insert into %s
						  (id,groupid,parentid,type,courseid,
						   departmentid,compare_unif_id,compare_unifint_id)
						(select u.id,groupid,parentid,type,courseid,
						        c.departmentid,
						        case when u.parentid is not null and u.type=6 then u.parentid else u.id end compare_unif_id,
						        case when u.parentid is not null then u.parentid else u.id end compare_unifint_id
						 from unit u join course_sis c on c.id=u.courseid
						 where c.enabled=1 and c.hidden=0 and u.hidden=0 and u.status=1)';

	public function Unit_cache_table($params=FALSE) {
		if ( $params !== FALSE )
			//Check for empty tables in the constructor
			//Do this for login and search handles else the code will not work
			$this->memtab = memory_table::get_instance($this->table_name, $this->update_sql, TRUE);
		else
			//Don't check for empty tables like when you don't need the cache data yet but still want to update it
			$this->memtab = memory_table::get_instance($this->table_name, $this->update_sql);
	}

	//Automatic update in every 30 minutes, 30 minutes is defined in memory_table but can be changed here
	//By pass the proper parameter to get_instance();
	//Delayed update, use this everything other than search handles
	function auto_update() {
		$this->memtab->auto_update();
	}

	//Do the update immediate if auto update time is up
	//Use this for search handles
	function auto_update_nodelay() {
		$this->memtab->auto_update(FALSE);
	}

	//Do the update now. Doesn't run if there was a update within the last 1 second, can change in get_instance().
	function update() {
		$this->memtab->update();
	}

	//Get the current active table unit_search_cache1 or unit_search_cache2
	function table() {
		return $this->memtab->table();
	}
}