<?php

namespace YesWiki\Meeo\Service;

include 'tools/meeo/libs/eleves/eleve.lib.php';

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use YesWiki\Bazar\Service\EntryManager;
use YesWiki\Bazar\Service\ListManager;
use YesWiki\Wiki;
use YesWiki\Meeo\Eleve\Eleve;

class EleveManager {

  private $formId;
  private $yunoshostFormId;
  private $entryManager;
  private $listManager;
  private $wiki;
  private $meeo_config;

  public function __construct( Wiki $wiki, ParameterBagInterface $params, EntryManager $entryManager, ListManager $listManager)
  {
    $this->meeo_config = $params->get('meeo');
    $this->wiki = $wiki;
    $this->formId = $this->meeo_config['elevesFormId'];
    $this->yunoshostFormId = $this->meeo_config['yunohostFormId'];
    $this->entryManager = $entryManager;
    $this->listManager = $listManager;
  }

  public function del($id) {
    $this->entryManager->delete($id);
  }

  public function updateEleve(Eleve $eleve) {
    $id = $eleve->getId();
    $data = $eleve->getData();
    $data['antispam'] = true;
    // echo var_dump($data);
    return $this->entryManager->update($id, $data);
  }

  public function getAll() {
    $eleves = [];
    foreach ($this->entryManager->search(['formsIds' => $this->formId]) as $data)
    {
      $eleve = new Eleve($this->entryManager, $this->meeo_config, $data);
      // echo "<p>".var_dump($eleve)."</p>";
      $eleves[] = $eleve;
    }
    return $eleves;
  }

  public function getEleve(string $id) {
    return new Eleve($this->entryManager, $this->meeo_config, $this->entryManager->getOne($id));
  }

  public function getCurrentEleve(string $username) {
    $all = $this->getAll();
    foreach ($all as $eleve) {
    // echo "<p>".var_dump($eleve)."</p>";
      if ($eleve->getUserId() == $username || $eleve->isParent($username))
        return $eleve;
    }
  }

  public function view() {
    $eleves = $this->getAll();
    // echo '<p>'.var_dump($eleves).'</p>';

    $classes = $this->listManager->getOne('ListeClasses');
    // echo "<p>".var_dump($classes)."</p>";
    return $this->wiki->render('@meeo/edu_eleves.twig', ['eleves' => $eleves, 'classes' => $classes['label']]);
  }
}