<?php


namespace App\Model\Services;


use App\Model\Entities\Components\Forum\Forum;
use App\Model\Entities\Components\Forum\Topic;
use App\Model\Entities\Security\User;
use App\Model\Entities\Templates\ForumTemplate;
use App\Model\Exceptions\Db\InvalidStateException;
use Kdyby\Doctrine\EntityRepository;

class ForumService extends BaseService
{
    /** @var  EntityRepository */
    protected $forums;
    /** @var  EntityRepository */
    protected $topics;

    protected function startup()
    {
        $this->forums = $this->getRepository(Forum::class);
        $this->topics = $this->getRepository(Topic::class);
    }

    /**
     * @param User $createdBy
     * @param string $name
     * @param null|string $description
     * @param ForumTemplate $template
     * @param Forum $parent
     * @param bool $publish
     * @return Forum
     * @throws InvalidStateException
     */
    public function createForum(User $createdBy, string $name, string $description = null, ForumTemplate $template = null, Forum $parent = null, bool $publish = false) : Forum
    {
        $forum = new Forum($createdBy);
        $forum->setTemplate($template);
        $forum->setParentForum($parent);
        $forum->setName($name);
        $forum->setDescription($description);

        if ($publish) {
            $forum->setState(Forum::ACTIVE);
        }

        $this->persist($forum);
        return $forum;
    }

    /**
     * @param $id
     * @return null|Forum
     */
    public function findForumById(int $id)
    {
        return $this->forums->find($id);
    }

    public function createTopic(User $createdBy, Forum $forum, string $title, string $description = null) : Topic
    {
        $topic = new Topic($createdBy, $forum);
        $topic->setTitle($title);
        $topic->setDescription($description);

        $this->persist($topic);
        return $topic;
    }

    /**
     * @param int $id
     * @return null|object
     */
    public function findTopicById(int $id)
    {
        return $this->topics->find($id);
    }

}