<?php
namespace Qii\Driver\Mysql;

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';
    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()
    {
        list($dbInfo, $useSlave) = $this->getDBInfoAndSalve();
        if (isset(self::$_readConnection[$dbInfo['db']]) && self::$_readConnection[$dbInfo['db']] != null) {
            return self::$_readConnection[$dbInfo['db']];
        }

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

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