<?php

namespace App\Manager;

use App\Core\Manager\EntityManager;
use App\Entity\Blog\Comment;
use App\Entity\Blog\Post;
use App\Entity\Blog\PostFollow;
use App\Factory\Blog\PostFollowFactory;
use App\Repository\Blog\PostFollowRepositoryQuery;

/**
 * class PostFollowManager.
 *
 * @author Simon Vieille <simon@deblan.fr>
 */
class PostFollowManager
{
    protected PostFollowFactory $factory;
    protected PostFollowRepositoryQuery $repository;
    protected EntityManager $manager;

    public function __construct(
        PostFollowFactory $factory,
        PostFollowRepositoryQuery $repository,
        EntityManager $manager
    ) {
        $this->factory = $factory;
        $this->repository = $repository;
        $this->manager = $manager;
    }

    public function create(Post $post, Comment $comment): PostFollow
    {
        $postFollow = $this->find($post, $comment);

        if (!$postFollow) {
            $postFollow = $this->factory->create($post, $comment);

            $this->manager->create($postFollow);
        }

        return $postFollow;
    }

    public function find(Post $post, Comment $comment): ?PostFollow
    {
        return $this->repository->create()
            ->where('.post = :post')
            ->andWhere('.comment = :comment')
            ->setParameters([
                ':post' => $post->getId(),
                ':comment' => $comment->getId(),
            ])
            ->findOne()
        ;
    }

    public function enable(PostFollow $postFollow): void
    {
        $postFollow->setIsEnabled(true);

        $this->manager->update($postFollow);
    }

    public function disable(PostFollow $postFollow): void
    {
        $this->manager->delete($postFollow);
    }
}
