<?php

namespace App\Service\Campaign\Keyword;

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

final class TagService
{
    /**
     * @var TagRepositoryInterface
     */
    private $repository;

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

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

        return $tag;
    }

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

        return $criteria;
    }

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

        return $tag;
    }

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