<?php


namespace App\Model\Facades\Readers;


use App\Model\Entities\Components\Forum\Forum;
use App\Model\Entities\Components\Forum\Topic;
use App\Model\Entities\Components\Post;
use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Services\ForumService;
use App\Model\Services\MessengerService;

class ForumReader extends BaseReader
{
    /** @var ForumService */
    protected $forumService;
    /** @var MessengerService */
    protected $messengerService;

    public function __construct(ForumService $forumService, MessengerService $messengerService)
    {
        $this->forumService = $forumService;
        $this->messengerService = $messengerService;
    }

    /**
     * @param int $id
     * @return Forum
     * @throws RecordNotFoundException
     */
    public function findForumById(int $id) : Forum
    {
        $forum = $this->forumService->findForumById($id);
        $this->validateEntity($forum);

        return $forum;
    }

    /**
     * @param $forum
     * @return Forum
     */
    public function validateForum($forum) : Forum
    {
        if ($forum instanceof Forum) {
            return $forum;
        }

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

    /**
     * @param int $id
     * @return Topic
     * @throws RecordNotFoundException
     */
    public function findTopicById(int $id) : Topic
    {
        $topic = $this->forumService->findTopicById($id);
        $this->validateEntity($topic);

        return $topic;
    }

    /**
     * @param $topic
     * @return Topic
     */
    public function validateTopic($topic) : Topic
    {
        if ($topic instanceof Topic) {
            return $topic;
        }

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

    public function findPostById($id) : Post
    {
        $post = $this->messengerService->findPostById($id);
        $this->validateEntity($post);

        return $post;
    }

    public function validatePost($post) : Post
    {
        if ($post instanceof Post) {
            return $post;
        }

        return $this->findPostById($post);
    }
}