<?php
 
/**
 * CDbCommandBuilder class file.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
 * @copyright 2008-2013 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

/**
 * CDbCommandBuilder provides basic methods to create query commands for tables.
 *
 * @property CDbConnection $dbConnection Database connection.
 * @property CDbSchema $schema The schema for this command builder.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package system.db.schema
 * @since 1.0
 */
class CommandBuilder extends CDbCommandBuilder {

    private $_schema;
    private $_connection;

    /**
     * @param CDbSchema $schema the schema for this command builder
     */
    public function __construct($schema) {
	$this->_schema = $schema;

	$this->_connection = $schema->getDbConnection();
    }

    /**
     * Creates an INSERT command.
     * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
     * @param array $data data to be inserted (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
     * @return CDbCommand insert command
     */
    public function createInsertCommand($table, $data) {
	$this->ensureTable($table);
	$fields = array();
	$values = array();
	$placeholders = array();
	$i = 0;
	$placeholders = '';
	foreach ($data as $name => $value) {
	    if (($column = $table->getColumn($name)) !== null && ($value !== null || $column->allowNull)) {
		$fields[] = $column->rawName;
		if ($value instanceof CDbExpression) {
		    $placeholders[] = $value->expression;
		    foreach ($value->params as $n => $v)
			$values[$n] = $v;
		} else {
		    $placeholders .= $value;
		    $placeholders .=','; //self::PARAM_PREFIX . $i;
		    // if (strpos($value, 'select') == false)
		    // $values[self::PARAM_PREFIX . $i] = $column->typecast($value);
//		    else
//			$values[self::PARAM_PREFIX . $i] = $value;
		    $i++;
		}
	    }
	}

	$placeholders = substr($placeholders, 0, -1);
	if ($fields === array()) {
	    $pks = is_array($table->primaryKey) ? $table->primaryKey : array($table->primaryKey);
	    foreach ($pks as $pk) {
		$fields[] = $table->getColumn($pk)->rawName;
		//$placeholders[] = $this->getIntegerPrimaryKeyDefaultValue();
	    }
	}
	$sql = "INSERT INTO {$table->rawName} (" . implode(', ', $fields) . ') VALUES (' . $placeholders . ')';
	$command = Yii::app()->db->createCommand($sql);

//	foreach ($values as $name => $value)
//	    $command->bindValue($name, $value);

	return $command;
    }

    /**
     * Creates an UPDATE command.
     * @param mixed $table the table schema ({@link CDbTableSchema}) or the table name (string).
     * @param array $data list of columns to be updated (name=>value)
     * @param CDbCriteria $criteria the query criteria
     * @throws CDbException if no columns are being updated for the given table
     * @return CDbCommand update command.
     */
    public function createUpdateCommand($table, $data, $criteria) {
	$this->ensureTable($table);
	$fields = array();
	$values = array();
	$bindByPosition = isset($criteria->params[0]);
	$i = 0;
	foreach ($data as $name => $value) {
	    if (($column = $table->getColumn($name)) !== null) {
		if ($value instanceof CDbExpression) {
		    $fields[] = $column->rawName . '=' . $value->expression;
		    foreach ($value->params as $n => $v)
			$values[$n] = $v;
		} elseif ($bindByPosition) {
		    $fields[] = $column->rawName . '=?';
		    $values[] = $column->typecast($value);
		} else {
		    if ($value == null)
			$value = 'null';
		    elseif ($name == 'date' || $name == 'segment_name')
			$value = "'" . $value . "'";
		    $fields[] = $column->rawName . '=' . $value;
//		    if (strpos($value, 'select') == false)
//			$values[self::PARAM_PREFIX . $i] = $column->typecast($value);
//		    else
		    //$values[self::PARAM_PREFIX . $i] = $value;
		    // $values[self::PARAM_PREFIX . $i] = $column->typecast($value);
		    $i++;
		}
	    }
	}
	if ($fields === array())
	    throw new CDbException(Yii::t('yii', 'No columns are being updated for table "{table}".',
			    array('{table}' => $table->name)));
    	$sql = "UPDATE {$table->rawName} SET " . implode(', ', $fields);
	$sql = $this->applyJoin($sql, $criteria->join);
	$sql = $this->applyCondition($sql, $criteria->condition);
	$sql = $this->applyOrder($sql, $criteria->order);
	$sql = $this->applyLimit($sql, $criteria->limit, $criteria->offset);

	$command = Yii::app()->db->createCommand($sql);
	//$this->bindValues($command, array_merge($values, $criteria->params));

	return $command;
    }

}
