<?php
/**
 * Paginig_handle_main.php
 *
 * The main class to manage all the paging handles.
 * This is mainly used to disable template page paging numbers based on conditions.
 *
 * @author $Author: dtong $
 * @version $Id: Paging_handle_main.php,v 1.2 2011/04/13 10:20:09 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/

Class Paging_handle_main {
	private $CI;

	function __construct() {
		$this->CI = & get_instance();
	}
	/*
	 * $template - The template object obtained from factory
	 * $data_input - The original $data passed to Unitmain constructor
	 * $pagenumber - The page number being checked
	 */
	function run($pagenumber, &$template, &$data_input) {
		if ( empty($template) || !is_object($template) || !osa_is_int($pagenumber) ) {
			osa_errorlog(__METHOD__ . " - Invalid input parameter current_page '{$pagenumber} or non-object template'");
			return osa_buildererror();
		}
		if ( isset($template->page_check) ) {
			//Only runs if there is a page check array
			if ( !is_array($template->page_check) ) {
				osa_errorlog(__METHOD__ . " - page_check is not an array.", $template->page_check);
				return osa_buildererror();
			}
			if ( isset($template->page_check[$pagenumber]) && is_array($template->page_check[$pagenumber]) ) {
				if ( array_key_exists('_handle', $template->page_check[$pagenumber]) ) {
					//Single handle and no need to be wrap in a array in the template file
					//So, put it in an array
					$handles = array($template->page_check[$pagenumber]);
				}
				else {
					//Multiple handles in an array
					$handles = & $template->page_check[$pagenumber];
				}
				foreach ($handles as $handle_check_array) {
					//Check to see if the page number requires checking
					//$handle_check_array = & $template->page_check[$pagenumber];
					if ( !isset($handle_check_array['_handle']) ) {
						osa_errorlog(__METHOD__ . " - Missing _handle index for page $pagenumber.", $handle_check_array);
						return osa_buildererror();
					}
					$handlename = 'paging_' . $handle_check_array['_handle'];
					//Load the handl object
					if (!@include_once("{$handlename}.php")) {
						osa_errorlog(__METHOD__ . " - Missing file {$handlename}.php.");
						return osa_buildererror();
					}
					$handleobj = & $this->CI->cms_cache->object_get($handlename);
					if ( empty($handleobj) ) {
						osa_errorlog(__METHOD__ . " - Handle class {$handlename} does not exist");
						return osa_buildererror();
					}
					//We init/reset the object. This allows us to reuse the object
					if ( !$handleobj->reset($pagenumber, $template, $handle_check_array, $data_input) ) {
						return osa_buildererror();
					}
					if ( !$handleobj->invoke() ) {
						return FALSE;
					}
				}//foreach
			}
		}
		return TRUE;
	}
}