<?php
namespace TYPO3\CMS\Workspaces\Controller;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Workspaces\Controller\Remote\ActionHandler;
use TYPO3\CMS\Workspaces\Controller\Remote\MassActionHandler;
use TYPO3\CMS\Workspaces\Controller\Remote\RemoteServer;

/**
 * Implements the AJAX functionality for the various asynchronous calls
 */
class AjaxDispatcher
{
    /**
     * @var array
     */
    protected $classMap = [
        'RemoteServer' => RemoteServer::class,
        'MassActions' => MassActionHandler::class,
        'Actions' => ActionHandler::class
    ];

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function dispatch(ServerRequestInterface $request, ResponseInterface $response)
    {
        $callStack = \GuzzleHttp\json_decode($request->getBody()->getContents());
        if (!is_array($callStack)) {
            $callStack = [$callStack];
        }
        $results = [];
        foreach ($callStack as $call) {
            $className = $this->classMap[$call->action];
            $method = $call->method;
            $parameters = $call->data;
            $instance = GeneralUtility::makeInstance($className);
            $results[] = $this->buildResultFromResponse(call_user_func_array([$instance, $method], $parameters), $call);
        }
        $response->getBody()->write(json_encode($results));
        return $response;
    }

    /**
     * @param mixed $responseFromMethod
     * @param \stdClass $call
     *
     * @return \stdClass
     */
    protected function buildResultFromResponse($responseFromMethod, $call)
    {
        $tmp = new \stdClass();
        $tmp->action = $call->action;
        $tmp->debug = '';
        $tmp->method = $call->method;
        $tmp->result = $responseFromMethod;
        $tmp->tid = $call->tid;
        $tmp->type = $call->type;
        return $tmp;
    }
}
