<?php

namespace Application\Model\Repository;

use Ainias\Core\Model\Repository\StandardRepository;
use Application\Controller\SyncController;
use Application\Model\Level;

class LevelRepository extends StandardRepository
{
    /**
     * @param \DateTime $date
     * @param int $offset
     * @return array
     */
    public function findNewerThanDate($date, $offset = 0)
    {
        $queryBuilder = $this->_em->createQueryBuilder();
        $queryBuilder->select("l")->from(Level::class, "l");

        if ($date != null)
        {
            $queryBuilder->andWhere($queryBuilder->expr()->gte("l.lastUpdated", ":fromDate"));
            $queryBuilder->setParameter("fromDate", $date->format("Y-m-d H:i:00"));
        }
        $queryBuilder->setMaxResults(SyncController::SYNC_MAX_LEVELS);
        $queryBuilder->setFirstResult($offset * SyncController::SYNC_MAX_LEVELS);

        return $queryBuilder->getQuery()->getResult();
    }

    public function countNewerThanDate($date)
    {
        $queryBuilder = $this->_em->createQueryBuilder();
        $queryBuilder->select("COUNT(l.id) as number")->from(Level::class, "l");

        if ($date != null)
        {
            $queryBuilder->andWhere($queryBuilder->expr()->gte("l.lastUpdated", ":fromDate"));
            $queryBuilder->setParameter("fromDate", $date->format("Y-m-d H:i:00"));
        }

        return $queryBuilder->getQuery()->getSingleScalarResult();
    }

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

    public function endTransaction()
    {
        try{
            $this->_em->getConnection()->commit();
        } catch (\Exception $e)
        {
            $this->_em->getConnection()->rollBack();
            throw $e;
        }
    }
}