<?php

namespace CCDN\Helpers\Api\Response;

/**
 * Class BaseResponse
 * @package CCDN\Helpers\Api\Response
 */
class Response implements ResponseInterface
{

    /**
     * @var array|null
     */
    private $data;

    private $value = "";

    /**
     * BaseResponse constructor.
     * @param  array  $data
     */
    public function __construct($data = [])
    {
        $this->data = $data;

        if (($name = $this->getField('name')) !== null) {
            $this->value = str_replace('"', '&quot;', $name);
        }
    }

    /**
     * @inheritDoc
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @inheritDoc
     */
    public function updateField($key, $value)
    {
        if (!isset($this->data[$key])) {
            return false;
        }
        $this->data[$key] = $value;

        return true;
    }

    /**
     * @inheritDoc
     */
    public function addField($key, $value)
    {
        if (isset($this->data[$key])) {
            return false;
        }
        $this->data[$key] = $value;

        return true;
    }

    /**
     * @inheritDoc
     */
    public function deleteField($key)
    {
        if (isset($this->data[$key])) {
            unset($this->data[$key]);
            return true;
        }
        return false;
    }

    /**
     * @inheritDoc
     */
    public function createFieldHandler($key, $item, $default)
    {
        $dataFromField = $this->getField($key);
        $dataFromField = $dataFromField !== null ? $dataFromField : $default;
        return new $item($dataFromField);
    }

    /**
     * @inheritDoc
     */
    public function getField($key)
    {
        return isset($this->data[$key]) ? $this->data[$key] : null;
    }

    /**
     * @inheritDoc
     */
    public function isEmpty()
    {
        return empty($this->data);
    }

    /**
     * @inheritDoc
     */
    public function getValue()
    {
        return $this->value;
    }
}
