<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Controller;

use Application\Admin\Widget\HttpWidgetInterface;
use Pongho\Http\Exception\HttpNotFoundException;

class WidgetsController extends AdminController
{
    public function indexAction(): never
    {
        throw new HttpNotFoundException();
    }

    /**
     * @param string $method
     * @return \Pongho\Http\Response
     */
    public function __call($method, array $args)
    {
        if (!str_ends_with($method, 'Action')) {
            throw new HttpNotFoundException();
        }

        $widget_name = substr($method, 0, -6);

        $collection = $this->getWidgetsCollection();
        if (!$collection->has($widget_name)) {
            throw new HttpNotFoundException();
        }

        $widget = $this->getWidgetsCollection()->get($widget_name);

        if ($widget instanceof HttpWidgetInterface) {
            return $widget->handleRequest($this->getRequest());
        }

        // @deprecated - usare l’interfaccia HttpWidgetInterface
        if (method_exists($widget, 'handleRequest')) {
            return $widget->handleRequest($this->getRequest());
        }

        throw new HttpNotFoundException();
    }

    /**
     * Restituisce l’elenco dei widget.
     *
     * @return \Application\Admin\Widget\WidgetsCollection
     */
    protected function getWidgetsCollection()
    {
        return $this->getContainer()->get('admin_dashboard_widgets');
    }
}
