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

use PHPUnit\Framework\TestCase;

class SqliteCapacitorTest extends TestCase {
  function _testChargeStrings(SqliteCapacitor $capacitor, ?string $channel) {
    $capacitor->reset($channel);
    $capacitor->charge("first", $channel);
    $capacitor->charge("second", $channel);
    $capacitor->charge("third", $channel);
    $items = iterator_to_array($capacitor->discharge($channel, false));
    self::assertSame(["first", "second", "third"], $items);
  }
  function _testChargeArrays(SqliteCapacitor $capacitor, ?string $channel) {
    $capacitor->reset($channel);
    $capacitor->charge(["id" => 10, "name" => "first"], $channel);
    $capacitor->charge(["name" => "second", "id" => 20], $channel);
    $capacitor->charge(["name" => "third", "id" => "30"], $channel);
  }

  function testChargeStrings() {
    $capacitor = new SqliteCapacitor(__DIR__.'/capacitor.db');
    $this->_testChargeStrings($capacitor, null);
    $capacitor->close();
  }

  function testChargeArrays() {
    $capacitor = new class(__DIR__.'/capacitor.db') extends SqliteCapacitor {
      protected function getKeyDefinitions(?string $channel): ?array {
        if ($channel === "arrays") {
          return ["id" => "integer"];
        }
        return parent::getKeyDefinitions($channel);
      }
      protected function getKeyValues($item, ?string $channel): ?array {
        if ($channel === "arrays") {
          return ["id" => $item["id"] ?? null];
        }
        return parent::getKeyValues($item, $channel);
      }
    };

    $this->_testChargeStrings($capacitor, "strings");
    $this->_testChargeArrays($capacitor, "arrays");
    $capacitor->close();
  }
}
