<?php

namespace Ignite\Core\Models\Menu;

use Ignite\Core\Contracts\CanDisplayInMenu;
use Ignite\Core\Events\Menus\ActionMenuPreCompile;
use Spatie\Menu\Laravel\Html;
use Spatie\Menu\Laravel\Link;

class ActionMenu extends Manager
{
    /** @var MenuExtended */
    private $menu;

    /**
     * Add a link to the menu.
     *
     * @param CanDisplayInMenu $item
     * @param MenuExtended $menu
     * @param bool $isFirstLevel
     */
    protected function addLink(CanDisplayInMenu $item, $menu, $isFirstLevel = false)
    {
        $link = $menu->link($item->getUrl(), $this->buildLabel($item));

        if ($isFirstLevel) {
            $link->addItemClass('btn btn-sm btn-default');
            $link->withoutParentTag();
        }
    }

    /**
     * Build the label for the link,
     *
     * @param  CanDisplayInMenu $item
     * @return string
     */
    protected function buildLabel(CanDisplayInMenu $item)
    {
        return Html::raw(sprintf(
            '<span class=""><i class="fa-solid fa-%s"></i> %s</span>',
            $item->getIcon(),
            $item->getLabel()
        ))->html();
    }

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

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

    /**
     * Render the menu.
     *
     * @param  array $context
     * @return string
     */
    public function render($context)
    {
        event(new ActionMenuPreCompile($this, $context));

        $this->menu = $this->buildMenu($this->getItems())
            ->setWrapperTag('div')
            ->addClass('btn-group')
            ->addParentClass('btn-group');

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