<?php

use Kirby\Cms\Structure;

trait tournament {
  /**
   * @kql-allowed
   */
  public function getRunningGames() {
    return $this->children()->filter(
      fn ($child) => $child->enddate()->isEmpty()
    );
  }

  /**
   * @kql-allowed
   */
  public function getStats($uuid) {
    $games = $this->children()->filter(
      fn ($child) => count($child->flatScorers()->filter( fn ($player) => $player->uuid()->toString() == $uuid ) )
    );
    $statsSum = [];
    foreach ($games as $key => $game) {
      if ($game->stats()->isEmpty() || $game->enddate()->isEmpty()) {
        continue;
      }
      $stats = $game->stats()->parseJSON()["stats"];
      $i = -1;
      foreach ($stats as $k => $stat) {
        if ($stat["player"] == $uuid) {
          $i = $k;
          break;
        }  
      }
      if ($i == -1){
        continue;
      }
      if (count($statsSum) == 0){
        $statsSum = $stats[$i];
        continue;
      }
      $statsSum = $game->addStats($statsSum, $stats[$i]);
    }
    return $statsSum;//$lol;//$stats[1]["player"]$player->uuid()->toString();
  }

  /**
   * @kql-allowed
   */
  public function scorers() {
    try {
      $scorers = $this->participants()->toStructure();
      return $scorers;
    } catch (\Throwable $th) {
      return Structure::factory(
        array_values($this->participants()->toPages()->sortBy('forename')->toArray(function($elem){
          return array("member" => array($elem->uuid()->toString()));
        })),
        ['parent' => $this, 'field' => $this->participants()]
      );
    }
  }
}
