<?php

namespace App\Service\Prospect;

use App\Entity\Prospect\Problem;
use App\Service\DataGrid\DataGridInterface;
use Doctrine\ORM\EntityNotFoundException;

final class ProblemService
{
    /**
     * @var ProblemRepositoryInterface
     */
    private $repository;

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

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

        return $problem;
    }

    /**
     * @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 int
     */
    public function countByGrid(DataGridInterface $dataGrid): int
    {
        $criteria = $this->getCriteria($dataGrid);

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

    /**
     * @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('prospect') && $dataGrid->getFilters()->get('prospect')->isValid()) {
            $criteria += ['prospect' => $dataGrid->getFilters()->get('prospect')->getValue()];
        }

        return $criteria;
    }

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

        return $problem;
    }

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