<?php
namespace nur\mapper\base\capacitor;

use PHPUnit\Framework\TestCase;

class CapacitorTest extends TestCase {
  function testPk() {
    $c = new Capacitor();
    $c->setKeys(["id" => true]);
    $c->charge(["id" => 1, "title" => "first"]);
    $c->charge(["id" => 1, "title" => "first (doublon)"]);
    self::assertSame([
      "1" => ["id" => 1, "title" => "first (doublon)"],
    ], $c->discharge());
  }

  function testSortSeq() {
    $items = [
      ["second", 4, 2, 1],
      ["hello", 1, 1, 4],
      ["first", 3, 1, 2],
      ["world", 2, 2, 3],
    ];
    $c = new Capacitor();
    foreach ($items as $item) {
      $c->charge($item);
    }

    $c->sort([1]);
    self::assertSame([
      ["hello", 1, 1, 4],
      ["world", 2, 2, 3],
      ["first", 3, 1, 2],
      ["second", 4, 2, 1],
    ], $c->discharge(null, false));

    $c->sort([2]);
    self::assertSame([
      ["hello", 1, 1, 4],
      ["first", 3, 1, 2],
      ["world", 2, 2, 3],
      ["second", 4, 2, 1],
    ], $c->discharge(null, false));

    $c->sort([3]);
    self::assertSame([
      ["second", 4, 2, 1],
      ["first", 3, 1, 2],
      ["world", 2, 2, 3],
      ["hello", 1, 1, 4],
    ], $c->discharge(null, false));

    $c->sort([2, 3]);
    self::assertSame([
      ["first", 3, 1, 2],
      ["hello", 1, 1, 4],
      ["second", 4, 2, 1],
      ["world", 2, 2, 3],
    ], $c->discharge(null, false));
  }

  function testSortAssoc() {
    $items = [
      ["hello", 1, 1, 4],
      ["world", 2, 2, 3],
      ["first", 3, 1, 2],
      ["second", 4, 2, 1],
    ];
    $c = new Capacitor();
    $c->setKeys([[0, true]]);
    foreach ($items as $item) {
      $c->charge($item);
    }

    $c->sort([1]);
    self::assertSame([
      "hello" => ["hello", 1, 1, 4],
      "world" => ["world", 2, 2, 3],
      "first" => ["first", 3, 1, 2],
      "second" => ["second", 4, 2, 1],
    ], $c->discharge(null, false));

    $c->sort([2]);
    self::assertSame([
      "hello" => ["hello", 1, 1, 4],
      "first" => ["first", 3, 1, 2],
      "world" => ["world", 2, 2, 3],
      "second" => ["second", 4, 2, 1],
    ], $c->discharge(null, false));

    $c->sort([3]);
    self::assertSame([
      "second" => ["second", 4, 2, 1],
      "first" => ["first", 3, 1, 2],
      "world" => ["world", 2, 2, 3],
      "hello" => ["hello", 1, 1, 4],
    ], $c->discharge(null, false));

    $c->sort([2, 3]);
    self::assertSame([
      "first" => ["first", 3, 1, 2],
      "hello" => ["hello", 1, 1, 4],
      "second" => ["second", 4, 2, 1],
      "world" => ["world", 2, 2, 3],
    ], $c->discharge(null, false));
  }
}