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

namespace Kufer\Web\Classes\Db;


class DBDirectUtility
{
  
  public $dboperation;
  
  public $dbtyp = 1;

  
  public function __construct($pDBnr = 1, $pNewInstance = false)
  {
    $this->dbtyp = $pDBnr;
    $this->dboperation = \DBOperation::getInstance($pDBnr, $pNewInstance, false);
    if ($this->dboperation->getDBName() !== 'MYSQL') {
      \Logger::logg('Jemand wollte das DBDirectUtility verwenden, aber nicht auf MySQL!', 4201);

      throw new \Exception('Diese Funktionalität ist bisher nur für MySQL vorgesehen');
    }
  }

  
  public function efficientInsertValuesIntoSingleColumnTable($pTableName, $pColumnName, $pValues)
  {
    if (!is_array($pValues)) {
      throw new \InvalidArgumentException('efficientInsertValuesToSingleColumnTable $pValues is not an array');
    }
    $swCount = count($pValues);
    $stepSize = 50;
    
    $sqlStart = 'INSERT IGNORE INTO ' . $pTableName . ' (' . $pColumnName . ') values ';
    for ($i = 0; $i < $swCount; $i += $stepSize) {
      
      $sql = $sqlStart;
      for ($j = 0; $j < $stepSize && $j + $i < $swCount; $j++) {
        $sql .= ' (\'' . $this->dboperation->getString4Sql(trim($pValues[$i + $j])) . '\'),';
      }
      $sql = \StringOperations::substr($sql, 0, -1) . ';';
      $this->dboperation->clear();
      $this->dboperation->query($sql);
    }
  }

  
  public function selectSeveralFieldsConcatenated($pTableName, $pIdColumnName, $pFields, $pWhere = '')
  {
    $idColumn = $this->dboperation->getString4Sql($pIdColumnName);
    $tableName = $this->dboperation->getString4Sql($pTableName);
    if ($idColumn === '' || $tableName === '') {
      \Logger::logg(
        'DBDirectUtility::selectSeveralFieldsConcatenated(): einer der Parameter ist leer: ' . "$pTableName, $pIdColumnName " . \DebugOperations::backtrace(),
        4101
      );

      return array();
    }
    $glue = ' ';
    $sqlpart = '';
    foreach ($pFields as $field) {
      $sqlpart .= $this->dboperation->getString4Sql($field) . ", '$glue', ";
    }
    $sql = 'SELECT ' . $idColumn . ', CONCAT(' . \StringOperations::substr($sqlpart, 0, -2) . ') as content FROM ' . $tableName;
    if ($pWhere !== '') {
      $sql .= $pWhere;
    }

    return $this->getSingleColumnDbResult($sql, 'content', $idColumn);
  }

  
  public function getSelectQueryBuilder()
  {
    return new \SelectQueryBuilder($this->dboperation);
  }

  
  public function getSingleColumnDbResult($pSql, $pContentColumnName, $pIdColumnName = '')
  {
    $this->dboperation->clear();
    $this->dboperation->query($pSql);
    $result = array();
    while ($this->dboperation->selectNextRow()) {
      $content = $this->dboperation->fieldbyname($pContentColumnName);
      if ($pIdColumnName === '') {
        $result[] = $content;
      } else {
        $result[$this->dboperation->fieldbyname($pIdColumnName)] = $content;
      }
    }

    return $result;
  }

  
  public function checkTableExistsOrCreate($pTableName, $pCreateStatement)
  {
    if ($this->dboperation->checkTableExists($pTableName)) {
      return true;
    }
    if ($pCreateStatement !== '' && \StringOperations::startsWith($pCreateStatement, 'create', false)) {
      $this->dboperation->clear();
      $this->dboperation->execute($pCreateStatement);

      return $this->dboperation->checkTableExists($pTableName, true);
    }

    return false;
  }

  
  public function truncateTable($pTableName)
  {
    $tableName = $this->dboperation->getString4Sql($pTableName);
    if ($this->dboperation->checkTableExists($tableName)) {
      $this->dboperation->clear();
      $this->dboperation->execute('TRUNCATE TABLE ' . $tableName);
    }
  }
}