<?php

namespace Application\Model\Manager;

use Ainias\Core\Model\Manager\StandardManager;
use Application\Model\Repository\LevelRepository;
use Application\Model\Level;

class LevelManager extends StandardManager
{
    /** @var LevelRepository  */
    protected $repository;

    public function __construct(LevelRepository $repository, Level $entity = null)
    {
        $this->repository = $repository;
        parent::__construct($repository, $entity);
    }

    /**
     * @param int $id
     * @return Level
     */
    public function getEntityById($id)
    {
        return parent::getEntityById($id);
    }

    public function beginTransaction()
    {
        $this->repository->beginTransaction();
    }

    public function endTransaction()
    {
        $this->repository->endTransaction();
    }

    /**
     * @param \DateTime $dateTime
     * @param int $offset
     * @return array
     */
    public function findNewerThan($dateTime, $offset = 0)
    {
        return $this->repository->findNewerThanDate($dateTime, $offset);
    }

    public function countNewerThan($dateTime)
    {
        return $this->repository->countNewerThanDate($dateTime);
    }

    public function levelToArray(Level $level)
    {
        return [
            "id" => $level->getId(),
            "words" => json_decode($level->getWords()),
            "rotations"=> json_decode($level->getPositions()),
            "lastUpdated" => $level->getLastUpdated()->format("Y-m-d"),
            "language" => $level->getLang(),
            "rendererType" => $level->getRenderer(),
            "difficulty" => $level->getDifficulty(),
            "deleted" => $level->isDeleted(),
        ];
    }

    public function levelsToArray($levels)
    {
        $returnArray = [];
        /** @var Level $level */
        foreach ($levels as $level)
        {
            $returnArray[] = $this->levelToArray($level);
        }
        return $returnArray;
    }
}