<?php
/*
 * static class
 */


class AjaxReq {


/*
 * Wygenerowanie id requestu dla ajaxowych requestow.
 * TODO: params ID_PROCES, ID_ZASOB_TABLE
 */
function generate_id( $proces_id, $tbl_zasob_id ) {
	$generate_uniq_ajax_req_id = '_tbl_'.uniqid();// uniq string eg. 4e9eaf7b82516

	self::_gc();

	if ($proces_id == 'CRM_LISTA_ZASOBOW') {
		$conf = array();
		$conf['proces_id'] = 'CRM_LISTA_ZASOBOW';
		$conf['step_id'] = 'CRM_LISTA_ZASOBOW';
		$conf['title'] = 'CRM_LISTA_ZASOBOW';

		$conf['sql_db'] = 'default';
		$conf['sql_table'] = 'CRM_LISTA_ZASOBOW';

		// TODO: read from wskazniki
		$allowed_cols = array();
		$allowed_cols ['ID']= 'ID';
		$allowed_cols ['PARENT_ID']= 'P_ID';
		$allowed_cols ['PARENT_ID_ACCESS']= 'P_ID2';
		$allowed_cols ['PARENT_ID_MAP']= 'P_ID3';
		$allowed_cols ['ALIAS_ID']= 'ALIAS';
		$allowed_cols ['TYPE']= 'TYPE';
		$allowed_cols ['DESC']= 'DESC';
		$allowed_cols ['OPIS']= 'OPIS';

		$sql_cols = array();
		foreach ($allowed_cols as $k_field => $v_label) {
			$sql_cols[$k_field] = '';
		}//end foreach

		$db = DB::getDB( $conf['sql_db'] );
		$sql = "show fields from `".$conf['sql_table']."`; ";
		$res = $db->query( $sql );
		while ($r = $db->fetch( $res )) {
			/**
				[Field] => ID
				[Type] => int(8)
				[Null] => NO
				[Key] => PRI
				[Default] => 
				[Extra] => auto_increment
			 */
			if (array_key_exists($r->Field, $sql_cols)) {
				$r->Perm = 'RWC';// TODO: raed from wskaznik.pytanie
				$r->Label = $allowed_cols[$r->Field];
				$sql_cols[ $r->Field ] = (array)$r;//json_encode( $r );
			}
		}
		$conf['sql_cols'] = $sql_cols;// ['sql_col_name'] = 'sql_name;perm;type;default';

		$conf['_last_access_time'] = time();// _gc
		$_SESSION['_ajax_req_id'] [$generate_uniq_ajax_req_id] = $conf;
	} else {
		trigger_error("App::generat_ajax_request_id: unknown tbl '$tbl_zasob_id'", E_USER_WARNING);
	}

	return $generate_uniq_ajax_req_id;
}


function &get_conf( $ajax_req_id ) {
	$ret = null;
	if (array_key_exists($ajax_req_id, $_SESSION['_ajax_req_id'])) {
		$_SESSION['_ajax_req_id'][ $ajax_req_id ]['_last_access_time'] = time();
		return $_SESSION['_ajax_req_id'][ $ajax_req_id ];
	}
	return $ret;
}


/*
 * Garbage collector - remove old ajax request from $_SESSION.
 */
function _gc() {
	$count_limit = 10;// TODO: limit na ilosc requestow - usuwac najstarsze
	$time_limit = 5 * 60;
	foreach ($_SESSION['_ajax_req_id'] as $ajax_req_id => $conf) {
		if (!isset($conf['_last_access_time'])) {// bad data
			unset($_SESSION['_ajax_req_id'][ $ajax_req_id ]);
		} else if (time() - $conf['_last_access_time'] > $time_limit) {// too old request
			unset($_SESSION['_ajax_req_id'][ $ajax_req_id ]);
		}
	}//end foreach
}


}// class
