<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\TaskBundle\Menu;

use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use Knp\Menu\MenuItem;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class MenuBuilder implements LocalMenuBuilderInterface
{
    /**
     * @var AuthorizationCheckerInterface
     */
    protected $authorizationChecker;

    /**
     * @var TranslatorInterface
     */
    protected $translator;

    public function __construct(
        AuthorizationCheckerInterface $authorizationChecker,
        TranslatorInterface $translator,
    ) {
        $this->translator = $translator;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function buildAccompanyingCourseMenu($menu, $parameters)
    {
        /** @var AccompanyingPeriod $course */
        $course = $parameters['accompanyingCourse'];

        if ($this->authorizationChecker->isGranted(TaskVoter::SHOW, $course)
            && AccompanyingPeriod::STEP_DRAFT !== $course->getStep()) {
            $menu->addChild(
                $this->translator->trans('Tasks'),
                [
                    'route' => 'chill_task_singletask_by-course_list',
                    'routeParameters' => ['id' => $course->getId()],
                ]
            )
                ->setExtra('order', 400);
        }
    }

    public function buildMenu($menuId, MenuItem $menu, array $parameters)
    {
        match ($menuId) {
            'person' => $this->buildPersonMenu($menu, $parameters),
            'accompanyingCourse' => $this->buildAccompanyingCourseMenu($menu, $parameters),
            'section' => $menu->setExtras('icons'),
            default => throw new \LogicException("this menuid {$menuId} is not implemented"),
        };
    }

    public function buildPersonMenu($menu, $parameters)
    {
        // var $person \Chill\PersonBundle\Entity\Person */
        $person = $parameters['person'] ?? null;

        if ($this->authorizationChecker->isGranted(TaskVoter::SHOW, $person)) {
            $menu->addChild(
                $this->translator->trans('Tasks'),
                [
                    'route' => 'chill_task_singletask_by-person_list',
                    'routeParameters' => ['id' => $person->getId()],
                ]
            )
                ->setExtra('order', 400);
        }
    }

    public static function getMenuIds(): array
    {
        return ['person', 'accompanyingCourse'];
    }
}
