<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

class UpdateQueryBuilder extends QueryBuilder
{
  private $table = '';
  private $setValues = array();
  private $where = '';

  public function update($table)
  {
    $this->table = $table . ' ';

    return $this;
  }

  public function setValues($keyValuesArray)
  {
    $this->setValues = $keyValuesArray;

    return $this;
  }

  public function where($sql)
  {
    $this->where = $sql . ' ';

    return $this;
  }

  
  public function addToWhere($sql)
  {
    if (trim($sql) != '') {
      $this->where .= $sql . ' ';
    }

    return $this;
  }

  
  public function addOperatorToWhere($sql, $op)
  {
    if (trim($sql) != '') {
      $trimmedwhere = trim($this->where);
      if ($trimmedwhere != '' && !\StringOperations::endsWith($trimmedwhere, '(')) {
        $this->addToWhere($op);
      }

      $this->addToWhere($sql);
    }

    return $this;
  }

  
  public function and($sql)
  {
    return $this->addOperatorToWhere($sql, 'AND');
  }

  
  public function or($sql)
  {
    return $this->addOperatorToWhere($sql, 'OR');
  }

  protected function getSQLString()
  {
    return $this->getUpdate() . $this->getSetValues() . $this->getWhere();
  }

  private function getUpdate()
  {
    return 'UPDATE ' . $this->table;
  }

  private function getSetValues()
  {
    $result = '';
    foreach ($this->setValues as $key => $value) {
      $result .= "$key = $value, ";
    }

    return 'SET ' . rtrim($result, ', ') . ' ';
  }

  private function getWhere()
  {
    if ($this->where != '') {
      return 'WHERE ' . $this->where;
    } else {
      return 'WHERE (1=1) ';
    }
  }

  
  public function getCondition()
  {
    return trim($this->where);
  }

  
  public function hasCondition()
  {
    return $this->where != '';
  }
}