<?php

namespace App\Service\Campaign;

use App\Entity\Campaign\Role;
use App\Service\DataGrid\DataGridInterface;
use Doctrine\ORM\EntityNotFoundException;

final class RoleService
{
    /**
     * @var RoleRepositoryInterface
     */
    private $repository;

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

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

        return $role;
    }

    /**
     * @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()];
        }

        return $criteria;
    }

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

        return $role;
    }

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