<?php
class DB {
	private $driver;
	private $cache;
	private $config;

	public function __construct($registry, $driver, $hostname, $username, $password, $database) {
		if (file_exists(DIR_DATABASE . $driver . '.php')) {
			require_once(DIR_DATABASE . $driver . '.php');
		} else {
			exit('Error: Could not load database file ' . $driver . '!');
		}

		$this->cache = $registry->get('cache');
		$this->config   = $registry->get('config');
		$this->driver = new $driver($hostname, $username, $password, $database);
	}

	public function setTimezone($timezone){
		$this->driver->setTimezone($timezone);
	}


	public function query($sql, $doCache = false, $typeTimeCache = false) {
		if($doCache){
			$cache = $this->cache->get(md5($sql));
			
			if($cache){
				$result = $cache;				
			}else{
				$result = $this->driver->query($sql);
				$this->cache->set(md5($sql), $result, $typeTimeCache);				
			}
		}else{
			$result =  $this->driver->query($sql);
		}

		return $result;
	}

	public function escape($value) {
		return $this->driver->escape($value);
	}

	public function escapeArray($data) {
    return $this->driver->escapeArray($data);
	}

	public function countAffected() {
		return $this->driver->countAffected();
	}

	public function getLastId() {
		return $this->driver->getLastId();
	}

	public function getConnectError(){
		return $this->driver->getConnectError();
	}

	public function startTransaction(){
		$this->driver->startTransaction();
	}

	public function commit(){
		$this->driver->commit();
	}

	public function rollback(){
		$this->driver->rollback();
	}

	public function dataAtual(){
		return $this->driver->dataAtual();
	}

	public function executeSql($query, array $args) {
    	return $this->driver->executeSql($query, $args);
	}

}
