<?php
namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Widget\Controller;

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\FluidAdaptor\Core\Widget\AbstractWidgetController;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\WeatherRepository;
use Newland\Toubiz\Sync\Neos\Service\WeatherService;
use Newland\Toubiz\Sync\Neos\Service\Weather\CopyrightService;

/**
 * The widget controller for the city list widget.
 */
class WeatherController extends AbstractWidgetController
{

    /**
     * @var WeatherRepository
     * @Flow\Inject()
     */
    protected $weatherRepository;

    /**
     * @var WeatherService
     * @Flow\Inject()
     */
    protected $weatherService;

    /**
     * @var CopyrightService
     * @Flow\Inject()
     */
    protected $copyrightService;

    /**
     * @var array
     */
    protected $cityDetailsConfiguration;

    public function initializeAction(): void
    {
        $this->cityDetailsConfiguration = $this->settings['cityDetails'];
    }

    /**
     * Main action for this widget.
     *
     * @return void
     */
    public function indexAction(): void
    {
        /** @var Article $article */
        $article = $this->widgetConfiguration['article'];

        if ($this->cityDetailsConfiguration['weather']['enabled'] === false) {
            return;
        }

        $city = $article->getName();

        if (empty($city)) {
            return;
        }

        $weather = $this->weatherService->findByCityArticle($article);
        $forecast = $weather ? $weather->getForecast() : [];
        $this->view->assignMultiple(
            [
                'article' => $article,
                'forecast' => $forecast,
                'mode' => $this->cityDetailsConfiguration['weather']['mode'] ?? null,
                'node' => $this->widgetConfiguration['node'],
                'copyrightInfo' => $this->copyrightService->getCopyrightInfo(),
            ]
        );
    }
}
