<?php

namespace idoit\Module\Forms\Model;

use Exception;
use idoit\Module\Forms\Exceptions\FormRequestBodyException;
use Symfony\Component\HttpFoundation\Response;

class FormRequestBodyDao
{
    /**
     * @var string
     */
    private $formId;

    /**
     * @var string
     */
    private $objectType;

    /**
     * @var array
     */
    private $formData = [];

    /**
     * @param string $formId
     * @param string $objectType
     * @param array $formData
     */
    public function __construct(string $formId, string $objectType, array $formData)
    {
        $this->formId = $formId;
        $this->objectType = $objectType;
        $this->formData = $formData;
    }

    /**
     * @return string
     */
    public function getFormId(): string
    {
      return $this->formId;
    }

    /**
     * @return string
     */
    public function getObjectType(): string
    {
      return $this->objectType;
    }

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

    /**
     * @return static
     * @throws FormRequestBodyException
     */
    public static function factory()
    {
        $body = file_get_contents('php://input');
        $requestBody = [];

        if (is_string($body) && \isys_format_json::is_json($body)) {
            $requestBody = \isys_format_json::decode($body);
        }

        if (isset($requestBody['form'], $requestBody['class'], $requestBody['data'])) {
            return new static($requestBody['form'], $requestBody['class'], $requestBody['data']);
        }

        throw new FormRequestBodyException("Malformed request body. One of the necessary parameters 'form', 'class', 'data' is not set!", Response::HTTP_BAD_REQUEST);
    }
}
