<?php

namespace App\Service;

use App\Entity\File;
use App\Service\DataGrid\DataGridInterface;
use Doctrine\ORM\EntityNotFoundException;

final class FileService
{
    /**
     * @var FileRepositoryInterface
     */
    private $repository;

    /**
     * FileService constructor.
     *
     * @param FileRepositoryInterface $repository
     */
    public function __construct(FileRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param int $id
     *
     * @return File
     *
     * @throws EntityNotFoundException
     */
    public function get(int $id): File
    {
        $file = $this->repository->findById($id);
        if (!$file) {
            throw new EntityNotFoundException('File with id '.$id.' does not exist!');
        }

        return $file;
    }

    /**
     * @return array|null
     */
    public function getAll(): ?array
    {
        return $this->repository->findAll();
    }

    /**
     * @return array|null
     */
    public function getByGrid(DataGridInterface $dataGrid): ?array
    {
        $criteria = $this->getCriteria($dataGrid);

        return $this->repository->findBy(
            $criteria,
            [
                $dataGrid->getSorters()->first()->getSort() => $dataGrid->getSorters()->first()->getOrder(),
            ],
            $dataGrid->getNavigation()->getRpp(),
            $dataGrid->getNavigation()->getRpp() * $dataGrid->getNavigation()->getPage());
    }

    /**
     * @param DataGridInterface $dataGrid
     *
     * @return array
     */
    private function getCriteria(DataGridInterface $dataGrid): array
    {
        $criteria = [];
        if ($dataGrid->getFilters()->containsKey('q') && $dataGrid->getFilters()->get('q')->isValid()) {
            $criteria += ['q' => $dataGrid->getFilters()->get('q')->getValue()];
        }

        if ($dataGrid->getFilters()->containsKey('title') && $dataGrid->getFilters()->get('title')->isValid()) {
            $criteria += ['title' => $dataGrid->getFilters()->get('title')->getValue()];
        }

        return $criteria;
    }

    /**
     * @param DataGridInterface $dataGrid
     *
     * @return int
     */
    public function countByGrid(DataGridInterface $dataGrid): int
    {
        $criteria = $this->getCriteria($dataGrid);

        return $this->repository->count($criteria);
    }

    /**
     * @param File $file
     *
     * @return File
     */
    public function save(File $file): File
    {
        $this->repository->save($file);

        return $file;
    }

    /**
     * @param File $file
     */
    public function delete(File $file): void
    {
        $this->repository->delete($file);
    }

    public function getByTitle(string $name)
    {
        return $this->repository->findOneBy(['title' => $name]);
    }
}
