<?php


namespace Trainingssystem\Module\Limesurvey\Api\Request;


use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Trainingssystem\Module\Limesurvey\Api\Model\Participant;

class AddParticipantRequest extends AbstractRequest implements Request
{
    /**
     * @var array
     */
    private $parameters;

    /**
     * @var array
     */
    private $participants;

    public function __construct(int $surveyId, Participant $participant, bool $createToken = true)
    {
        $this->parameters = [
            'iSurveyID' => $surveyId,
            'aParticipantData' => [[
                'firstname' => $participant->getFirstname(),
                'lastname' => $participant->getLastname(),
                'email' => $participant->getEmail(),
            ]],
            'bCreateToken' => $createToken,
        ];
    }

    public function getMethod(): string
    {
        return 'add_participants';
    }

    public function getParameters(): array
    {
        return $this->parameters;
    }

    public function handleResponse($response): void
    {
        $this->response = $response;

        $serializer = new Serializer([new ObjectNormalizer(), new ArrayDenormalizer()]);
        $this->participants = $serializer->denormalize($this->response, 'Trainingssystem\Module\Limesurvey\Api\Model\Participant[]');
    }

    public function isValid(): bool
    {
        return !isset($this->response['status']);
    }

    public function getError(): string
    {
        return $this->response['status'];
    }

    /**
     * @return array
     */
    public function getParticipants(): array
    {
        return $this->participants;
    }
}