<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Db;

use Kufer\Web\Classes\Datamodul\InformationSchemaTable;

class DBWorkInformationSchemaTables extends \DBWorkGenerated
{
  public function __construct($pDBnr = 1, $pNewInstance = false)
  {
    parent::__construct($pDBnr, $pNewInstance);

    $this->_dataModulFields = array('table_name', 'create_time');
    $this->select = implode(', ', $this->_dataModulFields);
  }

  public function getTableName(): string
  {
    return 'information_schema.TABLES';
  }

  public function getNewObject()
  {
    return new InformationSchemaTable();
  }

  public function getAllQuery(): \SelectQueryBuilder
  {
    $builder
     = $this->getSelectQueryBuilder()
      ->select($this->select)
      ->from($this->getTableName())
      ->paramRaw('table', $this->getTableName());

    $varDb = $builder->uniqueVar();

    return $builder
      ->and(":table:.TABLE_SCHEMA = :$varDb:")
      ->paramString($varDb, $this->dboperation->connectionInfo->db_name);
  }

  public function getTemporaryKuferTransferTablesQuery(int $staleSinceHours = 12): \SelectQueryBuilder
  {
    $underscore = $this->dboperation->dbparser->escapeCharInLike('_');

    $staleDateTime = \DateTimeOperations::addHours(\DateTimeOperations::getDateTimeNow(), -$staleSinceHours);

    return $this->getAllQuery()
      ->andExpr(function(\SelectQueryBuilder $builder) {
        return $builder
          ->or('TABLE_NAME LIKE :likeTmpTable:' . $this->dboperation->dbparser->escapeClauseForLike())
          ->or('TABLE_NAME LIKE :likeTmpTableOld:' . $this->dboperation->dbparser->escapeClauseForLike());
      })
      ->and('CREATE_TIME <= :staledate:')
      ->paramString('likeTmpTable', "%{$underscore}tmp%{$underscore}____")
      ->paramString('likeTmpTableOld', "%{$underscore}tmp%{$underscore}____{$underscore}old")
      ->paramDateTime('staledate', $staleDateTime);
  }

  
  public function getTemporaryKuferTransferTables(int $staleSinceHours = 12): array
  {
    $builder = $this->getTemporaryKuferTransferTablesQuery($staleSinceHours);

    $this->dboperation->clear();
    if (!$this->dboperation->query($builder->getSQL(), false)) {
      return array(); 
    }

    return $this->getAllRowsStream()->filter(static function(InformationSchemaTable $table): bool {
      return preg_match('/^.*_tmp[1-9][0-9]+_.{4}(_old)?$/', $table->table_name) === 1;
    })->toArray();
  }

  public function hasTemporaryKuferTransferTables(int $staleSinceHours = 12): bool
  {
    return count($this->getTemporaryKuferTransferTables($staleSinceHours)) > 0;
  }
}