<?php

namespace App\Service;

use App\Entity\Client;
use App\Repository\Client\ClientRepositoryInterface;
use App\Service\DataGrid\DataGridInterface;
use Doctrine\ORM\EntityNotFoundException;

final class ClientService
{
    /**
     * @var ClientRepositoryInterface
     */
    private $clientRepository;

    /**
     * ClientService constructor.
     *
     * @param ClientRepositoryInterface $clientRepository
     */
    public function __construct(ClientRepositoryInterface $clientRepository)
    {
        $this->clientRepository = $clientRepository;
    }

    /**
     * @param int $clientId
     *
     * @return Client
     *
     * @throws EntityNotFoundException
     */
    public function getClient(int $clientId): Client
    {
        $client = $this->clientRepository->findById($clientId);
        if (!$client) {
            throw new EntityNotFoundException('Client with id '.$clientId.' does not exist!');
        }

        return $client;
    }

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

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

        return $this->clientRepository->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 countClientsByGrid(DataGridInterface $dataGrid): int
    {
        $criteria = [];
        if ($dataGrid->getFilters()->containsKey('q') && $dataGrid->getFilters()->get('q')->isValid()) {
            $criteria += ['q' => $dataGrid->getFilters()->get('q')->getValue()];
        }

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

    /**
     * @param Client $client
     *
     * @return Client
     */
    public function saveClient(Client $client): Client
    {
        $this->clientRepository->save($client);

        return $client;
    }

    /**
     * @param Client $client
     */
    public function deleteClient(Client $client): void
    {
        $this->clientRepository->delete($client);
    }
}
