<?php
require_once 'app/class-log-management.php';

/**
 * Entity Manager
 *
 * granst common operation
 *
 * @author ba - Advantis Solutions
 * @version 1.0.1
 * @package Base
 */
class EntityManager {
	public $internal_name;
	private $configkey;
	
	/**
	 * constructor
	 *
	 * @param unknown $name        	
	 * @param string $configkey        	
	 */
	function EntityManager($name, $configkey = null) {
		$this->internal_name = $name;
		$this->configkey = $configkey;
	}
	
	/**
	 * Loads data as query from DB Model
	 *
	 * @param string $filter        	
	 * @param unknown $values        	
	 * @return multitype:
	 */
	function load($filter = '', $values = array()) {
		$da = new DataAccess ( $this->configkey );
		
		$r = $da->query_get ( array (
				'entity' => $this->internal_name,
				'filter' => $filter,
				'values' => $values 
		) );
		
		$list = array ();
		
		if (is_array($r)){
			foreach ( $r as $line ) {
			
				$entity = new Entity ( $this->internal_name );
			
				foreach ( $line as $key => $value ) {
				
					$entity->$key = $value;
				}
			
				array_push ( $list, $entity );
			}			
		}

		return $list;
	}
	
	/**
	 * Creates new entry on DB Model from entity param
	 *
	 * @param unknown $obj        	
	 * @return void|unknown|Entity
	 */
	function create($obj) {
		if (Authorization::context_access_mode () == __ACCESS_READ) {
			
			return;
		}
		
		$da = new DataAccess ( $this->configkey );
		
		$newid = $da->create ( array (
				'entity' => $this->internal_name,
				'obj' => $obj 
		) );
		
		// log
		if ($this->internal_name != "logs") {
			
			LogManagement::log_entity ( $this, "create" );
		}
		// ---
		
		$childEntityClass = get_class ( $obj );
		if (isset ( $childEntityClass ) && $childEntityClass != 'Entity' && $childEntityClass != 'stdClass') {
			return new $childEntityClass ( $newid, $this->configkey );
		} else {
			return new Entity ( $this->internal_name, $newid, $this->configkey );
		}
	}
	
	/**
	 * Deletes entry on DB Model from entity param
	 *
	 * @param unknown $obj        	
	 * @return void|boolean
	 */
	function delete($obj) {
		if (Authorization::context_access_mode () == __ACCESS_READ) {
			
			return;
		}
		
		$da = new DataAccess ( $this->configkey );
		
		$res = $da->delete ( array (
				'entity' => $this->internal_name,
				'obj' => $obj 
		) );
		
		// log
		if ($this->internal_name != "logs") {
			
			LogManagement::log_entity ( $this, "delete" );
		}
		// ---
		
		if ($res === false) {
			return false;
		} else {
			return true;
		}
	}
}

?>