<?php declare(strict_types=1);

namespace Newland\Toubiz\Services\Neos\Controller;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Mvc\View\ViewInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Service;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ServiceRepository;

class ServiceTeaserController extends ActionController
{

    /**
     * @var ServiceRepository
     * @Flow\Inject()
     */
    protected $serviceRepository;

    /**
     * @var NodeInterface
     */
    protected $node;

    public function initializeView(ViewInterface $view): void
    {
        /** @var NodeInterface|null $node */
        $node = $this->request->getInternalArgument('__node');
        if ($node !== null) {
            $this->node = $node;
        }
        $view->assign('node', $this->node);
    }

    /**
     * @param Service[] $services
     * @param string[] $ids
     * @return Service[]
     */
    private function applySortByIds(array $services, array $ids): array
    {
        usort($services, function (Service $a, Service $b) use ($ids) {
            $idA = $a->getPersistenceObjectIdentifier();
            $idB = $b->getPersistenceObjectIdentifier();
            $indexA = array_search($idA, $ids, true);
            $indexB = array_search($idB, $ids, true);

            if ($indexA == $indexB) {
                return 0;
            } elseif ($indexA > $indexB) {
                return 1;
            } else {
                return -1;
            }
        });

        return $services;
    }

    public function listAction(): void
    {
        $ids = $this->node->getProperty('services') ?? [];
        $services = $this->serviceRepository->findByIdentifiers($ids);
        $services = $this->applySortByIds((array) $services, $ids);

        $this->view->assignMultiple(
            [
                'services' => $services,
                'enableSwiper' => $this->node->getProperty('displayStyle') === 'swiper',
            ]
        );
    }

    public function showAction(): void
    {
        $serviceId = $this->node->getProperty('service');
        $service = $this->serviceRepository->findByIdentifier($serviceId);

        $this->view->assignMultiple([
            'service' => $service,
            'slots' => $this->request->getInternalArgument('__slots'),
        ]);
    }
}
