<?php
/**
 * Searchmain.php - The main library for interfacing various components for mapping
 *
 * @author $Author: dtong $
 * @version $Id: Searchmain.php,v 1.8 2011/03/17 14:16:39 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('configfactory.php');
require_once('input_page.php');

Class Searchmain {
	//private $CI=NULL;
	private $config=NULL;

	function __construct() {
		//$this->CI = & get_instance();
		$this->config = configfactory::factory();
	}

	/*
	 * Gets all necessary template data for generating the menu buttons
	 */
	function getmenu() {
		$CI = & get_instance();
		//Piggyback on the generic menu handle
		$CI->load->library('menu/event/menu_handle_main');
		$config = $this->config;
		$result = array();
		foreach ($config->search as $key=>$item) {
			if ( !is_array($config->search[$key]) || !array_key_exists(0, $config->search[$key]) ) {
				//Make sure we have index 0
				osa_errorlog(__METHOD__ . " - Index zero missing for key $key", $config->search);
				continue;
			}
			$tmp = $config->search[$key][0];
			//Event handle '_handle'
 			if ( $CI->menu_handle_main->run($tmp) == FALSE ) {
 				continue;
 			}
			$result[$key] = $tmp;
		}
		return $result;
	}

	/*
	 * Renders one search page based on the the index from the url
	 */
	function input_page($index) {
		if ( ($data = $this->get_page_data($index)) === FALSE || !is_array($data) || count($data) < 2 ||
			  !array_key_exists(0, $data) || !array_key_exists(1, $data) ) {
			osa_errorlog(__METHOD__ . " - Failed to get data for index $index");
			return FALSE;
		}
		$CI = & get_instance();
		//Piggyback on the generic menu handle
		$CI->load->library('menu/event/menu_handle_main');
		//Check the index 0 for handle
		if ( $CI->menu_handle_main->run($data[0]) == FALSE ) {
 			return FALSE;
 		}
 		$data_mod = $data;
 		//Check each array inside index 1 for handle and unset if necessary
 		foreach ($data[1] as $key => $value) {
 			if ( !$CI->menu_handle_main->run($value) ) {
				unset($data_mod[1][$key]);
 			}
 		}
		$pageobj = new input_page($data_mod);
		return $pageobj->render();
	}

	/*
	 * Gets the template search data according to the index
	 */
	private function get_page_data($index) {
		if (array_key_exists($index, $this->config->search))
			return $this->config->search[$index];
		return FALSE;
	}

}
?>