<?php

namespace Diamond\Modules\Menu;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\ModuleController;
use Diamond\Application\User\UserService;
use Propel\Runtime\Map\TableMap;
use \Diamond\Services\Access;
use Diamond\Repositories\Menu as MenuRepo;

/**
 * Class Menu
 * @package Diamond\Modules\Menu
 */
Class Menu extends ModuleController implements RequestAwareInterface
{
    use RequestAwareTrait;
    /**
     *
     * Признак Авторизации
     *
     * @var bool
     */
    public $auth = false;

    public $title = '';

    /**
     * @var string
     */
    public $name = '';

    /**
     * @var string
     */
    public $class = 'menu';

    /**
     * Принудительное указание активного эелемента меню
     * @var bool
     */
    public $force_current = false;

    /**
     *
     * @var \Diamond\Repositories\Menu
     */
    protected $menuRepo;

    /**
     * @var Access
     */
    protected $accessService;

    public function __construct(MenuRepo $menuRepo, UserService $accessService
    )
    {
        $this->menuRepo = $menuRepo;
        $this->accessService = $accessService;
    }


    public function process(): string
    {

        if (empty($this->name)) {
            return false;
        }

        $itemsF = $this
            ->menuRepo
            ->findByName($this->name)
            ->toArray(null, false, TableMap::TYPE_CAMELNAME);

        $menuItems = [];

        foreach ($itemsF as $k => $Item) {
            $menuItems[$Item['url']>''?md5($Item['url'].$Item['title']):md5($Item['id'])] = $Item;
        }

        $items = array_values($menuItems);

        $items = $this->prepareItems($items);

        $this
            ->addData('collapsed', $this->request->cookies->get('leftmenu') === 'collapsed')
            ->addData('name', $this->name)
            ->addData('items', $items)
            ->addData('auth', $this->auth)
            ->addData('class', $this->class)
            ->addData('title', $this->title);

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


    protected function prepareItems(array $items, bool $useValidRights = true): array
    {

        $tree_items = array();

        foreach ($items as $k => $item) {


            if ($useValidRights === true && !$this->accessService->isUserAccessMenu($item['id'], UserService::ACCESS_READ)) {
                continue;
            }

            if ($this->force_current && $this->force_current === $item['code']) {
                $item['current'] = true;
            } elseif ($this->force_current && strpos($item['url'],$this->force_current)!==false) {
                $item['current'] = true;
            } elseif (!$this->force_current && $this->request->getPathInfo() === $item['url']) {
                $item['current'] = true;
            } else {
                $item['current'] = false;
            }

            if ($item['parentId'] > 0) {
                $tree_items[$item['parentId']]['subitems'][] = $item;
            } elseif (!isset($tree_items[$item['id']])) {
                $tree_items[$item['id']] = $item;
            } else {
                $item['subitems'] = $tree_items[$item['id']]['subitems'];
                $tree_items[$item['id']] = $item;
            }

            unset($items[$k]);
        }

        return $tree_items;
    }

}
