<?php

declare(strict_types=1);

namespace Cin\Quickpurchase\classes;

final class QueueList
{
  private array $list;

  /**
   * @param QueueItem[] $queueItems
   */
  public function __construct(?array $queueItems = null)
  {
    $this->list = $queueItems ?? [];
    array_walk($this->list, static function (&$item): void {
      if ('object' === \gettype($item) && 'Cin\Purchaseportal\classes\QueueItem' !== \get_class($item)) {
        $item = new QueueItem($item);
      }
    });
  }

  public function Add(QueueItem $queueItem): void
  {
    $this->list[] = $queueItem;
  }

  /**
   * @param callable(QueueItem $queueItem, int $index):void $callback
   */
  public function Foreach(callable $callback): void
  {
    foreach ($this->list as $idx => $queueItem) {
      $callback($queueItem, $idx);
    }
  }

  public function ToJson()
  {
    $data = [];
    $this->Foreach(static function (QueueItem $queueItem) use (&$data): void {
      $data[] = json_decode($queueItem->__toString());
    });

    // return json_encode($data);
    return $data;
  }
}
