<?php
global $_,$conf;
switch($_['action']){

	case 'factory_search_part':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Template.class.php');
			$i = 0;
			foreach(Template::all($_['template']) as $key=>$template): 
				$response['rows'][] = array(
					'active' => $i==0,
					'langage' =>  $template['syntax'],
					'label' => $key
				);
				$i++; 
			endforeach; 
		});
	break;

	case 'factory_search_filters':
		Action::write(function(&$response){
			global $myUser,$_;
			require_once(__DIR__.SLASH.'Template.class.php');
			$response['rows']  = array();
		
			$sections = array();
			foreach (Template::all($_['template']) as $template) {
				$stream = file_get_contents($template['file']);
				preg_match_all('/{{~!?([^}]*)}}/i', $stream, $matches,PREG_SET_ORDER);
				
				foreach($matches as $section)
					$sections[] = array('section'=>trim($section[1]));
			}
			
			$sections = array_map("unserialize", array_unique(array_map("serialize", $sections)));
			sort($sections);
			$response['rows'] = $sections;
		});
	break;

	case 'factory_autocomplete_plugin':
		Action::write(function(&$response){
			global $myUser,$_;
			$response['rows']  = array();
			foreach(glob(__ROOT__.PLUGIN_PATH.'*') as $plugin){
				if(!is_dir($plugin)) continue;
				$plugin = basename($plugin);
				if(preg_match('|'.$_['keyword'].'|i', $plugin)) $response['rows'][] = array('name'=>$plugin,'value'=>$plugin);
			}
		});
	break;

	case 'factory_entity_search':
		Action::write(function(&$response){
			global $myUser,$_;
			$response['rows']  = array();

			foreach(glob(__ROOT__.PLUGIN_PATH.$_['plugin'].SLASH.'*.class.php') as $entity){
				if(is_dir($entity)) continue;
				$entity = str_replace('.class.php','',basename($entity));
				
				$response['rows'][] = $entity;
			}
		});
	break;

	case 'factory_autocomplete_entity':
		Action::write(function(&$response){
			global $myUser,$_;
			$response['rows']  = array();

			foreach(glob(__ROOT__.PLUGIN_PATH.$_['plugin'].SLASH.'*.class.php') as $entity){
				if(is_dir($entity)) continue;
				$entity = str_replace('.class.php','',basename($entity));
				
				if(preg_match('|'.$_['keyword'].'|i', $entity)) $response['rows'][] = array('name'=>$entity,'value'=>$entity);
			}
		});
	break;
	case 'factory_autocomplete_entity_select':
		Action::write(function(&$response){
			global $myUser,$_;
			$response['rows']  = array();
			$path = __ROOT__.PLUGIN_PATH.$_['plugin'].SLASH.$_['entity'].'.class.php';
			if(!file_exists($path)) return;

			//new version via fields object
			require_once($path);
			$item = new $_['entity']();
			$sgbd = BASE_SGBD;
			$types = array_keys($sgbd::types());
			foreach ($item->fields as $field => $type) {
				if(in_array($field, array('id', 'created', 'updated', 'creator', 'updater'))) continue;
				if(!in_array($type, $types)) continue;
				$response['rows'][] = array('label'=>$field, 'type'=>$type);
			}

			//Old version via preg_match
			// $stream = file_get_contents($path);
			// preg_match_all('|\'([^\']*)\' \=\> \'([^\']*)\',?|ism', $stream , $matches,PREG_SET_ORDER);
			// foreach ($matches as $match) {
			// 	if($match[1]=='id') continue;
			// 	if(count($match)!=3) continue;
			// 	$response['rows'][] = array('label' => $match[1],'type' => $match[2]);
			// }
		});
	break;

	case 'factory_render':
		
		global $myUser;
		require_once(__DIR__.SLASH.'Template.class.php');

		$entity = factory_sanitize($_['entity']);
		$table = factory_sanitize($_['entity'], true);
		$plugin = factory_sanitize($_['plugin']);
		$description = isset($_['description']) ? $_['description'] : '';
		$fields =  array();
		$links =  array();
		
		$types = Template::types();

		if(isset($_['fields'])){
			foreach ($_['fields']  as $key => $value){
				if($key=='' || $key==1)continue;
				if($value['label']=='') $value['label'] = ucfirst($key);
				
				
				$value['key'] = lcFirst(factory_sanitize($key));
			
				if(strpos($value['type'], 'entity-')!==false){
					$type = $types['int'];
					$links[] = array('key'=>$value['key'],'entity'=>str_replace('entity-','',$value['type']));
				}else{
					$type = $types[$value['type']];
				}

				$value['typeLabel'] = $type['label'];


				$value['sql-type'] = $type['sql-type'];
				$value['input'] = factory_render($type['input'],$value);

				$fields[lcfirst(factory_sanitize($key))] = $value;
			}
		}
		$filters = array();


		if(isset($_['filters'])){
			foreach ($_['filters']  as $key => $value){
				if($value == '')continue;
				$filters[] = $value;
			}
		}

		$templates = Template::all($_['template']);
		$template = $templates[$_['part']];


		$data = array(
			'Entity' => $entity,
			'entity' => strtolower($entity),
			'ENTITY' => strtoupper($entity),
			'table' => $table,
			'user.fullname' => $myUser->fullName(),
			'user.mail' => $myUser->mail,
			'plugin' => strtolower($plugin),
			'PLUGIN' => strtoupper($plugin),
			'Plugin' => ucfirst(strtolower($plugin)),
			'fields' => $fields,
			'links' => $links,
			'linksCount' => count($links)> 0 ? 1: 0,
			'filters' => $filters,
			'description' => $description,
		);

		foreach(array('-','_','.') as $symbol){
			$readable = factory_sanitize(str_replace(' ',$symbol,trim($_['entity'])),false,'_.-');
			$readable = mb_strtolower($readable);
			if(strpos($readable,$plugin.$symbol) === 0)
				$readable = substr($readable, strlen($plugin.$symbol));

			$data['entity'.$symbol.'readable'] = $readable;
		}
		
		$stream = file($template['file']);
		array_shift($stream);
		$stream = implode($stream);
		$stream = factory_render($stream,$data);
		if(isset($_['generate']) && $_['generate']==1){

			if(!isset($_['plugin']) || !isset($_['entity'])) return;

			$relativePath = str_replace(Template::dir($_['template']),'',$template['file']);
			$relativePath = factory_render($relativePath,$data);

			$pluginPath = PLUGIN_PATH.strtolower($plugin);
			$filePath = $pluginPath.SLASH.$relativePath;
		
			$parentFolder = dirname($filePath);
			if(!file_exists($parentFolder)) mkdir($parentFolder,0755,true);
			file_put_contents($filePath,$stream);
		}
		echo htmlentities($stream);
	break;
}

?>