<?php


namespace App\Model\Services;


use App\Model\Entities\Components\Forum\Forum;
use App\Model\Entities\Components\Gallery\Gallery;
use App\Model\Entities\Components\Navigation\BaseNavItem;
use App\Model\Entities\Components\Navigation\NavItemForum;
use App\Model\Entities\Components\Navigation\NavItemGallery;
use App\Model\Entities\Components\Navigation\NavItemNews;
use App\Model\Entities\Components\News\NewsContainer;
use App\Model\Entities\Interfaces\INavItem;
use App\Model\Interfaces\ISite;
use Kdyby\Doctrine\EntityRepository;

class NavigationService extends BaseService
{
    /** @var  EntityRepository */
    protected $items;

    protected function startup()
    {
        $this->items = $this->getRepository(BaseNavItem::class);
    }

    /**
     * @param ISite $site
     * @return null|INavItem
     */
    public function findHomepage(ISite $site)
    {
        return $this->items->findOneBy(['site' => $site, 'isHomepage' => true]);
    }

    /**
     * @param $site
     * @return INavItem[]
     */
    public function getNavigation(ISite $site) : array
    {
        return $this->items->findBy(['site' => $site], ['itemOrder' => 'ASC']);
    }

    public function attachNews(ISite $site, NewsContainer $newsContainer, string $label, string $icon = null) : NavItemNews
    {
        $navItem = new NavItemNews();
        $navItem->setSite($site);
        $navItem->setNews($newsContainer);
        $navItem->setLabel($label);
        $navItem->setIcon($icon);
        $navItem->setItemOrder($this->getNextOrder($site) + 1000);

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

    public function attachGallery(ISite $site, Gallery $gallery, string $label, string $icon = null) : NavItemGallery
    {
        $navItem = new NavItemGallery();
        $navItem->setSite($site);
        $navItem->setGallery($gallery);
        $navItem->setLabel($label);
        $navItem->setIcon($icon);
        $navItem->setItemOrder($this->getNextOrder($site) + 1000);

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

    public function attachForum(ISite $site, Forum $forum, string $label, string $icon = null) : NavItemForum
    {
        $navItem = new NavItemForum();
        $navItem->setSite($site);
        $navItem->setForum($forum);
        $navItem->setLabel($label);
        $navItem->setIcon($icon);
        $navItem->setItemOrder($this->getNextOrder($site) + 1000);

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

    protected function getNextOrder(ISite $site)
    {
        return $this->items->createQueryBuilder('i')->where('i.site = :site')->setParameter('site', $site)->select('MAX(i.itemOrder)')->getQuery()->getSingleScalarResult();
    }

}