<?php


namespace App\Model\Services;


use App\Model\Entities\Components\News\News;
use App\Model\Entities\Components\News\NewsContainer;
use App\Model\Entities\Localization\Language;
use App\Model\Entities\Security\User;
use App\Model\Entities\Templates\NewsTemplate;
use Kdyby\Doctrine\EntityRepository;

class NewsService extends BaseService
{
    /** @var  EntityRepository */
    protected $containers;
    /** @var  EntityRepository */
    protected $news;

    protected function startup()
    {
        $this->containers = $this->getRepository(NewsContainer::class);
        $this->news = $this->getRepository(News::class);
    }

    /**
     * @param int $id
     * @return null|NewsContainer
     */
    public function findContainerById(int $id)
    {
        return $this->containers->find($id);
    }

    /**
     * @param int $id
     * @return null|News
     */
    public function findNewsById(int $id)
    {
        return $this->news->find($id);
    }

    /**
     * @param NewsContainer $container
     * @return News[]
     */
    public function getNews(NewsContainer $container) : array
    {
        return $this->news->findBy(['container' => $container, 'state' => News::PUBLISHED], ['publishedAt' => 'DESC']);
    }

    /**
     * @param NewsTemplate $template
     * @param User $createdBy
     * @param string $name
     * @return NewsContainer
     */
    public function createContainer(User $createdBy, NewsTemplate $template, string $name) : NewsContainer
    {
        $container = new NewsContainer($createdBy);
        $container->setTemplate($template);
        $container->setName($name);

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

    public function createNews(User $createdBy, NewsContainer $container, Language $language, string $title, string $description, string $content) : News
    {
        $news = new News($createdBy);
        $news->setContainer($container);
        $news->setLanguage($language);
        $news->setTitle($title);
        $news->setDescription($description);
        $news->setContent($content);

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

}