<?php


namespace App\Model\Facades\Readers;


use App\Model\Entities\Components\News\News;
use App\Model\Entities\Components\News\NewsContainer;
use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Services\NewsService;

class NewsReader extends BaseReader
{
    /** @var NewsService */
    protected $newsService;

    public function __construct(NewsService $newsService)
    {
        $this->newsService = $newsService;
    }

    /**
     * @param int $id
     * @return NewsContainer
     * @throws RecordNotFoundException
     */
    public function findContainerById(int $id) : NewsContainer
    {
        $container =  $this->newsService->findContainerById($id);
        $this->validateEntity($container);

        return $container;
    }

    public function findNewsById(int $id) : News
    {
        $news = $this->newsService->findNewsById($id);
        $this->validateEntity($news);

        return $news;
    }

    /**
     * @param $container
     * @return News[]
     */
    public function getNews($container) : array
    {
        $containerEntity = $this->validateContainer($container);

        return $this->newsService->getNews($containerEntity);
    }

    /**
     * @param $newsContainer
     * @return NewsContainer
     */
    public function validateContainer($newsContainer) : NewsContainer
    {
        if ($newsContainer instanceof NewsContainer) {
            return $newsContainer;
        }

        return $this->findContainerById($newsContainer);
    }

    public function validateNews($news) : News
    {
        if ($news instanceof News) {
            return $news;
        }

        return $this->findNewsById($news);
    }

}