<?php

namespace Ignite\Core\Models\Menu;

use Ignite\Core\Contracts\CanDisplayInMenu;
use Ignite\Core\Events\Menus\NavigationMenuPreCompile;
use Spatie\Menu\Laravel\Link;
use Spatie\Menu\Laravel\Menu as SpatieMenu;

class NavigationMenu extends Manager
{
    /** @var SpatieMenu */
    protected $menu;

    /**
     * Add a link to the menu.
     *
     * @param CanDisplayInMenu $item
     * @param SpatieMenu $menu
     */
    public function addLink(CanDisplayInMenu $item, $menu)
    {
        $link = $menu->linkIf($item->canBeViewed(), $item->getUrl(), $this->buildLabel($item));
        $link->addItemParentClass('page-nav-item');
        $link->setActiveClass('page-nav-item--active');
        $link->setActive(function ($link) use ($item, $menu) {
            /** @var \Spatie\Menu\Link $link */
            if ($link->url() === url()->current()) {
                return true;
            }

            $isNotHomepage = url($link->url()) !== url('/');
            $containsUrl = str_contains(url()->current(), $link->url());

            if ($isNotHomepage && $containsUrl && ! $menu->isExactActive()) {
                return true;
            }

            return false;
        });
    }

    /**
     * Build the label for the link,
     *
     * @param  CanDisplayInMenu $item
     * @return string
     */
    protected function buildLabel(CanDisplayInMenu $item)
    {
        return $item->getLabel();
    }

    /**
     * Build a submenu link.
     *
     * @param  CanDisplayInMenu $item
     * @return Link
     */
    public function addSubmenuLink(CanDisplayInMenu $item)
    {
        return Link::to('#' . $item->getUrl(), sprintf('%s <span class="caret"></span>', $item->getLabel()))
            ->addClass('dropdown-toggle')
            ->setAttribute('data-toggle', 'dropdown')
            ->setAttribute('aria-haspopup', 'true')
            ->setAttribute('aria-expanded', 'false');
    }

    /**
     * Build the menu.
     *
     * @param  \Illuminate\Support\Collection|array $links
     * @return SpatieMenu
     */
    public function buildMenu($links)
    {
        return MenuExtended::build($links, function ($menu, CanDisplayInMenu $item) {
            if (! $item->hasChildren()) {
                $this->addLink($item, $menu);
            } else {
                $menu->submenu(
                    $this->addSubmenuLink($item),
                    $this->buildMenu($item->getChildren())
                         ->addClass('dropdown-menu page-nav-dropdown')
                         ->addParentClass('page-nav-item page-nav-item--has-dropdown dropdown')
                );
            }
        });
    }

    /**
     * Render the menu.
     */
    public function render()
    {
        event(new NavigationMenuPreCompile($this));

        $this->menu = $this->buildMenu($this->getItems())->addClass('page-nav-list page-nav--right');

        return $this->menu->render();
    }
}
