<?php


namespace Trainingssystem\Module\Limesurvey\Api;


use Graze\GuzzleHttp\JsonRpc\Exception\RequestException;
use Trainingssystem\Module\Limesurvey\Api\Request\GetSessionKeyRequest;
use Trainingssystem\Module\Limesurvey\Api\Request\Request;

class LimesurveyApi
{
    /**
     * @var Connection
     */
    private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    public static function create()
    {
        return new self(new GuzzleHttpConnection());
    }

    /**
     * @param Request $request
     * @throws \Exception
     */
    public function request(Request $request)
    {
        // get session key
        $pluginOptions = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS, []);
        $username = $pluginOptions['limesurvey_rpc_username'] ?? '';
        $password = $pluginOptions['limesurvey_rpc_password'] ?? '';

        $sessionRequest = new GetSessionKeyRequest($username, $password);
        $this->performRequest($sessionRequest);
        $sessionKey = $sessionRequest->getSessionKey();

        // perform main request
        $this->performRequest($request, $sessionKey);
    }

    /**
     * @param Request $request
     * @throws \Exception
     */
    private function performRequest(Request $request, string $sessionKey = '')
    {
        $pluginOptions = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS, []);
        $url = $pluginOptions['limesurvey_rpc_url'] ?? '';

        $parameters = $request->getParameters();
        $parameters = $sessionKey !== '' ? array_merge(['sSessionKey' => $sessionKey], $parameters) : $parameters;

        $response = $this->connection->sendRequest($url, $request->getMethod(), $parameters);
        $request->handleResponse($response);
        if (!$request->isValid($response)) {
            throw new \Exception($request->getError());
        }
    }
}