<?php
namespace nur\mapper\base;

use nur\A;
use nur\mapper\base\oobd\IOobdManager;

class mark_utils {
  static function compute($item, ?array $keys): string {
    $item = A::with($item);
    if ($keys === null) $keys = array_keys($item);
    $parts = [];
    foreach ($keys as $key) {
      $part = A::get($item, $key);
      if (is_array($part)) {
        $part = "[".self::compute($part, null)."]";
      } else {
        $part = strval($part);
      }
      $parts[] = $part;
    }
    return sha1(implode("|", $parts));
  }

  static function set_use_marks(IOobdManager $manager, ?string $prefix=null, bool $shared=true): void {
    $manager->setOvalue("mark:$prefix:have_marks", true, $shared);
  }

  static function is_use_marks(IOobdManager $manager, ?string $prefix=null): bool {
    return boolval($manager->getOvalue("mark:$prefix:have_marks"));
  }

  static function set_use_keys_for_item_marked(IOobdManager $manager, ?array $keys, ?string $prefix=null): void {
    $manager->setOvalue("mark:$prefix:keys", $keys);
  }

  static function set_item_marked(IOobdManager $manager, $item, ?string $prefix=null, bool $shared=true): void {
    $keys = $manager->getOvalue("mark:$prefix:keys");
    $mark = self::compute($item, $keys);
    $manager->setOvalue("mark:$prefix:marks:$mark", true, $shared);
    $manager->setOvalue("mark:$prefix:have_marks", true, $shared);
  }

  static function is_item_marked(IOobdManager $manager, $item, ?string $prefix=null): bool {
    $keys = $manager->getOvalue("mark:$prefix:keys");
    $mark = self::compute($item, $keys);
    return boolval($manager->getOvalue("mark:$prefix:marks:$mark"));
  }
}
