<?php
/**
 * @author Jaap Jansma <jaap.jansma@civicoop.org>
 * @license AGPL-3.0
 */

namespace Civi\DataProcessor\Storage;

use Civi;
use CRM_Core_DAO;
use CRM_Dataprocessor_ExtensionUtil as E;

class TemporaryDatabaseTable extends DatabaseTable {

  /**
   * @param string $table
   * @param int $expireTime
   *   In seconds. Default to 4 hours (14 400 seconds)
   */
  public function __construct(string $table, int $expireTime = 14400) {
    $temporaryTables = Civi::settings()->get(E::SHORT_NAME.'_temporary_tables');
    if (empty($temporaryTables)) {
      $temporaryTables = [];
    }
    if (!isset($temporaryTables[$table])) {
      $temporaryTables[$table]['table_name'] =  'temp_' . E::SHORT_NAME.'_'.md5($table);
    }
    $temporaryTables[$table]['expires'] = time() + $expireTime;
    Civi::settings()->set(E::SHORT_NAME.'_temporary_tables', $temporaryTables);

    parent::__construct($temporaryTables[$table]['table_name']);
  }

  public static function dropAllExpiredTables(): int {
    $temporaryTables = Civi::settings()->get(E::SHORT_NAME.'_temporary_tables');
    if (empty($temporaryTables)) {
      $temporaryTables = [];
    }
    $count = 0;
    foreach($temporaryTables as $key => $table) {
      if ($table['expires'] < time()) {
        CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS `" . $table['table_name']."`");
        unset($temporaryTables[$key]);
        $count ++;
      }
    }
    Civi::settings()->set(E::SHORT_NAME.'_temporary_tables', $temporaryTables);
    return $count;
  }

  public function dropTable() {
    $temporaryTables = Civi::settings()->get(E::SHORT_NAME.'_temporary_tables');
    if (empty($temporaryTables)) {
      $temporaryTables = [];
    }
    foreach($temporaryTables as $key => $table) {
      if ($table['table_name'] == $this->table) {
        CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS `" . $table['table_name']."`");
        unset($temporaryTables[$key]);
      }
    }
    Civi::settings()->set(E::SHORT_NAME.'_temporary_tables', $temporaryTables);
  }

}
