<?php
namespace nur\sery\db\sqlite;

use nur\sery\db\CapacitorChannel;
use nur\sery\db\CapacitorStorage;

/**
 * Class SqliteStorage
 */
class SqliteStorage extends CapacitorStorage {
  function __construct($sqlite) {
    $this->db = Sqlite::with($sqlite);
  }

  /** @var Sqlite */
  protected $db;

  function db(): Sqlite {
    return $this->db;
  }

  const PRIMARY_KEY_DEFINITION = [
    "id_" => "integer primary key autoincrement",
  ];

  function _getCreateSql(CapacitorChannel $channel): string {
    $query = new _query_base($this->_createSql($channel));
    return self::format_sql($channel, $query->getSql());
  }

  protected function _afterCreate(CapacitorChannel $channel): void {
    $db = $this->db;
    $db->exec([
      "create table if not exists",
      "table" => "_channels",
      "cols" => [
        "name" => "varchar primary key",
        "table_name" => "varchar",
        "class" => "varchar",
      ],
    ]);
    $db->exec([
      "insert",
      "into" => "_channels",
      "values" => [
        "name" => $channel->getName(),
        "table_name" => $channel->getTableName(),
        "class" => get_class($channel),
      ],
      "suffix" => "on conflict do nothing",
    ]);
  }

  protected function _beforeReset(CapacitorChannel $channel): void {
    $this->db->exec([
      "delete",
      "from" => "_channels",
      "where" => [
        "name" => $channel->getName(),
      ],
    ]);
  }

  function _exists(CapacitorChannel $channel): bool {
    $tableName = $this->db->get([
      "select name from sqlite_schema",
      "where" => [
        "name" => $channel->getTableName(),
      ],
    ]);
    return $tableName !== null;
  }

  function close(): void {
    $this->db->close();
  }
}
