<?php
namespace Qii\Driver\Mysqli;

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

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

    /**
     * @var resource $_writeConnection  获取写的链接
     */
    protected static $_writeConnection = null;
    /**
     * @var resource$_readConnection 获取读的链接
     */
    protected static $_readConnection = null;

	public function __construct()
	{
		$this->_dbInfo = Register::getAppConfigure(Register::get(Consts::APP_DB));
	}

	/**
	 * 获取读数据的连接资源
	 */
	public function getReadConnection()
	{
        if (self::$_readConnection != null) {
            return self::$_readConnection;
        }
        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();

		if ($useSlave) {
			try {
				$connection = mysqli_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
				if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysqli_connect_error())), true);
				mysqli_select_db($connection, $dbInfo['db']);
				return self::$_readConnection = $connection;
			} catch (Exception  $e) {
				return $this->getWriteConnection();
			}
		}
		return $this->getWriteConnection();
	}

	/**
	 * 获取写数据的连接资源
	 *
	 */
	public function getWriteConnection()
	{
        if (self::$_writeConnection != null) {
            return self::$_writeConnection;
        }
		$dbInfo = $this->_dbInfo['master'];
		try {
			$connection = @mysqli_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
			if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysqli_connect_error())), true);
			mysqli_select_db($connection, $dbInfo['db']);
			return self::$_writeConnection = $connection;
		} catch (Exception  $e) {
			throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], toUTF8($e->getMessage())), __LINE__);
		}
	}
}