<?php
namespace Engine\Db;

class Connection
{
	public function __construct()
	{

	}

	public function getConnector(?\Engine\Db\Credentials $credentialsObj = null)
	{
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		if ($credentialsObj===null) {
			$credentialsObj = new \Engine\Db\Credentials();
			$credentialsObj->loadDefaultCredentials();
		}
		$credentials = $credentialsObj->getCredentials();

		$connection = ADONewConnection($credentials['type']);
		$connection->Connect($credentials['host'], $credentials['user'], $credentials['pass'], $credentials['name']);

		if ($connection->IsConnected()) {
			// fetch type
			$connection->SetFetchMode(ADODB_FETCH_ASSOC);

			// if set to count queries
			$connection->fnExecute = 'AdodbExecute';

			// SET ENCODINGS ------------------------------------------------------------------------------
			if ($CFG['encodings']['dbConnectCharset']) {
				$connection->Execute("SET NAMES " . $CFG['encodings']['dbConnectCharset']);
				if ($connection->ErrorNo()) {
					throw new \DBException("Cannot set db names charset");
				}
			}

			if ($CFG['encodings']['dbConnectCharset']) {
				$connection->Execute("SET CHARACTER SET " . $CFG['encodings']['dbConnectCharset']);
				if ($connection->ErrorNo()) {
					throw new \DBException("Cannot set db encodings charset");
				}
			}

			if ($CFG['encodings']['dbConnectCollation']) {
				$connection->Execute("SET COLLATION_CONNECTION = '" . $CFG['encodings']['dbConnectCollation']."'");
				if ($connection->ErrorNo()) {
					throw new \DBException("Cannot set db collation");
				}
			}

			// SET TIMEZONE
			$connection->Execute("SET time_zone =  ? ", date('P') );
			if ($connection->ErrorNo()) {
				throw new \DBException("Cannot set db time zone");
			}

			// set (force) sql mode
			$connection->Execute("SET sql_mode = 'NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION'");
			if ($connection->ErrorNo()) {
				throw new \DBException("Cannot set db sql mode");
			}
		}

		return $connection;
	}
}