<?php

declare(strict_types=1);

namespace App\Service\Domain;

use App\Entity\Domain\TopicTrustFlow;
use Doctrine\ORM\EntityNotFoundException;

final class TopicTrustFlowService
{
    /**
     * @var TopicTrustFlowRepositoryInterface
     */
    private $repository;

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

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

        return $topicTrustFlow;
    }

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

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

    /**
     * @param TopicTrustFlow $topicTrustFlow
     *
     * @return TopicTrustFlow
     */
    public function save(TopicTrustFlow $topicTrustFlow): TopicTrustFlow
    {
        if (!$this->repository->findBy(['domain' => $topicTrustFlow->getDomain(), 'topic' => $topicTrustFlow->getTopic(), 'value' => $topicTrustFlow->getValue()])) {
            $this->repository->save($topicTrustFlow);
        }

        return $topicTrustFlow;
    }
}
