<?php
/**
 * 数据库连接类
 *
 * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-12-10 14:42
 */
namespace Qii\Driver\Pdo;

use Qii\Config\Consts;
use Qii\Config\Register;
use Qii\Driver\ConnBase;
use Qii\Driver\ConnIntf;
use Qii\Exceptions\Errors;

class Connection extends ConnBase implements ConnIntf
{
	const VERSION = '1.2';

	public function __construct($dbInfo = array())
	{
        Register::mergeAppConfigure(Register::getAppConfigure(Consts::APP_DB), $dbInfo);
		$this->_dbInfo = Register::getAppConfigure(Register::get(Consts::APP_DB));
		if(!isset($this->_dbInfo['use_db_driver'])) $this->_dbInfo['use_db_driver'] = 'mysql';
	}

	/**
	 * 获取读数据的连接资源
	 * @return \PDO
	 */
	public function getReadConnection()
	{
        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
        if (isset(self::$_readConnection[$dbInfo['db']]) && self::$_readConnection[$dbInfo['db']] != null) {
            return self::$_readConnection[$dbInfo['db']];
        }
		if ($useSlave) {
			try {
				if ($this->_dbInfo['use_db_driver'] == 'mssql') {
					$dsn = 'odbc:Driver={SQL Server};Server=' . $dbInfo['host'] . ';Database=' . $dbInfo['db'] . ';';
				} else {
					$dsn = $this->_dbInfo['use_db_driver'] . ":host=" . $dbInfo['host'] . ";dbname=" . $dbInfo['db'];
				}
				return self::$_readConnection[$dbInfo['db']] = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
			} catch (Exception  $e) {
				return $this->getWriteConnection();
			}
		}
		return $this->getWriteConnection();
	}

	/**
	 * 获取写数据的连接资源
	 * @return res
	 */
	public function getWriteConnection()
	{
        $dbInfo = $this->_dbInfo['master'];
	    if (isset(self::$_writeConnection[$dbInfo['db']]) && self::$_writeConnection[$dbInfo['db']] != null) {
	        return self::$_writeConnection[$dbInfo['db']];
        }
		try {
			if ($this->_dbInfo['use_db_driver'] == 'mssql') {
				$dsn = 'odbc:Driver={SQL Server};Server=' . $dbInfo['host'] . ';Database=' . $dbInfo['db'] . ';';
			} else {
				$dsn = $this->_dbInfo['use_db_driver'] . ":host=" . $dbInfo['host'] . ";dbname=" . $dbInfo['db'];
			}
			return self::$_writeConnection[$dbInfo['db']] = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
		} catch (Exception  $e) {
			throw new Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], toUTF8($e->getMessage())), __LINE__);
		}
	}
}