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

use Qii\Driver\ConnBase;
use Qii\Driver\ConnIntf;

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

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

	/**
	 * 获取读数据的连接资源
	 * @return \PDO
	 */
	public function getReadConnection()
	{
        if (self::$_readConnection != null) {
            return self::$_readConnection;
        }
        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
		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'];
				}
				self::$_readConnection = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
                return self::$_readConnection;
			} catch (Exception  $e) {
				return $this->getWriteConnection();
			}
		}
		return $this->getWriteConnection();
	}

	/**
	 * 获取写数据的连接资源
	 * @return res
	 */
	public function getWriteConnection()
	{
	    if (self::$_writeConnection != null) {
	        return self::$_writeConnection;
        }
		$dbInfo = $this->_dbInfo['master'];
		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 = new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
		} catch (Exception  $e) {
			throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], toUTF8($e->getMessage())), __LINE__);
		}
	}
}