<?php

namespace Snaju\Inception\Http\Response\Formatters;

use Snaju\Inception\Http\Response\Enums\ResponseFormat;
use Snaju\Inception\Http\Response\Response;

class JsonResponseFormatter implements ResponseFormatterInterface
{

    const CONTENT_TYPE_JSON = 'application/json; charset=UTF-8';

    const CONTENT_TYPE_JSONP = 'application/javascript; charset=UTF-8';

    public ?string $contentType;

    public bool $useJsonP = false;

    public int $encodeOptions = 320;

    public bool $prettyPrint = false;

    public function __construct(array $options = [])
    {

    }

    public function format(Response $response)
    {
        if ($response->format === ResponseFormat::JSONP) {
            $this->contentType = self::CONTENT_TYPE_JSONP;
            $this->useJsonP = true;
        }
            else {
                $this->contentType = self::CONTENT_TYPE_JSON;
            }

        $response->getHeaderCollection()->add('Content-Type', $this->contentType);

        if ($this->useJsonP) {
            $this->formatJsonP($response);
        }
            else {
                $this->formatJson($response);
            }
    }

    private function formatJson(Response $response)
    {
        if ($response->data !== null) {
            $options = $this->encodeOptions;
            if ($this->prettyPrint) {
                $options |= JSON_PRETTY_PRINT;
            }
            $response->content = json_encode($response->data, $options);
        }
            elseif ($response->content === null) {
                $response->content = 'null';
            }
    }

    public function formatJsonP(Response $response)
    {

    }

}