<?php


namespace Mainto\RpcServer\Protocol\Response\Extend;


use Mainto\RpcServer\Protocol\Common\MapReadWrite;
use Mainto\RpcServer\Protocol\Response\Extend;
use Mainto\RpcServer\Protocol\Response\HeaderExtend;
use Mainto\RpcServer\Util\IO\Reader;
use Mainto\RpcServer\Util\IO\Writer;

class ResponseExtendHeader implements HeaderExtend {
    private array $header = [];

    public function magicNum () {
        return Extend::MagicNumUrlInvoke;
    }

    public function addHeader (string $key, string $value) {
        if (strlen($key) < 255 && strlen($value) < 65535) {
            if (!isset($this->header[$key])) {
                $this->header[$key] = [];
            }

            $this->header[$key][] = $value;
        }
    }

    public function setHeader (string $key, array $values) {
        if (strlen($key) > 255) {
            return;
        }

        foreach ($values as $value) {
            if ($value >= 65535) {
                return;
            }
        }

        $this->header[$key] = $values;
    }

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

    /**
     * @param string $key
     * @return array
     */
    public function getHeader (string $key): array {
        return $this->header[$key];
    }

    public function writeHeaderTo (Writer $writer): int {
        return MapReadWrite::littleWriteMapTo($this->header, $writer);
    }

    public function readHeaderFrom (Reader $reader): int {
        return MapReadWrite::littleReadMapFrom($this->header, $reader);
    }

    public function toArray (): array {
        return [
            'type'   => 'ResponseExtendHeader',
            'header' => $this->header,
        ];
    }

    public function dumpToWriter (Writer $writer) {
        return json_encode($this->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
}