<?php


namespace Mainto\RpcServer\Protocol\Request\Extend;


use Mainto\RpcServer\Protocol\Common\MapReadWrite;
use Mainto\RpcServer\Protocol\Request\BodyExtend;
use Mainto\RpcServer\Protocol\Request\Extend;
use Mainto\RpcServer\Protocol\Request\HeaderExtend;
use Mainto\RpcServer\Protocol\Request\QueryExtend;
use Mainto\RpcServer\Util\IO\Reader;
use Mainto\RpcServer\Util\IO\Writer;

class RequestExtendUrlInvoke extends RequestExtendHeader implements HeaderExtend, BodyExtend, QueryExtend {
    private array $query = [];
    private array $file = [];

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

    public function checkParams () {
    }

    public function setQuery(string $key, array $values) {
        $this->checkAndSet($this->query, $key, $values);
    }

    public function addQuery(string $key, string $value) {
        $this->checkAndAdd($this->query, $key, $value);
    }

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

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

    public function addFile(string $key, Reader $reader) {
        $this->file[$key] = $reader;
    }

    public function writeBodyTo (Writer $writer): int {
        if ($this->file) {
            throw new \RuntimeException("current not support file upload");
        }

        return 0;
    }

    public function readBodyFrom (Reader $reader): int {
        // todo current not support file upload
        return 0;
    }

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

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

    public function toArray (): array {
        return array_replace(parent::toArray(), [
            'type'   => 'RequestExtendUrlInvoke',
            'query' => $this->query,
        ]);
    }

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