<?php

namespace CCDN\Helpers\Api\Response\Field;

class IframeUlrField implements IframeUrlFieldInterface
{
    /**
     * @var string|null
     */
    private $iframeUrl;

    /**
     * @var string|null
     */
    private $iframeUrlQuery;

    /**
     * IframeUlr constructor.
     * @param string|null $iframeUrl
     */
    public function __construct($iframeUrl = '')
    {
        $this->iframeUrl = $iframeUrl;
        $this->_updateIframeQuery();
    }

    /**
     * @return void
     */
    private function _updateIframeQuery()
    {
        $this->iframeUrlQuery = parse_url($this->iframeUrl, PHP_URL_QUERY);
    }

    /**
     * @inheritDoc
     */
    public function addQueryParam($key, $value)
    {

        if (empty($key) || !isset($value) || $value === '' || $this->isEmpty()) {
            return $this;
        }

        parse_str($this->iframeUrlQuery, $urlQueryArr);

        $urlQueryArr = array_merge($urlQueryArr, [
            $key => $value
        ]);

        $httpQuery = http_build_query($urlQueryArr);

        if (empty($this->iframeUrlQuery)) {
            $this->iframeUrl .= '?' . $httpQuery;
        } else {
            $this->iframeUrl = str_replace($this->iframeUrlQuery, $httpQuery, $this->iframeUrl);
        }

        $this->_updateIframeQuery();

        return $this;
    }

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

    /**
     * @inheritDoc
     */
    public function removeQueryParam($key)
    {
        if (empty($this->iframeUrlQuery) || $this->isEmpty()) {
            return $this;
        }

        parse_str($this->iframeUrlQuery, $urlQueryArr);

        if (isset($urlQueryArr[$key])) {
            unset($urlQueryArr[$key]);
        } else {
            return $this;
        }

        if (empty($urlQueryArr)) {
            $this->iframeUrl = str_replace('?' . $this->iframeUrlQuery, '', $this->iframeUrl);
            return $this;
        }

        $httpQuery = http_build_query($urlQueryArr);
        $this->iframeUrl = str_replace($this->iframeUrlQuery, $httpQuery, $this->iframeUrl);
        $this->_updateIframeQuery();

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function clearQuery()
    {
        if (empty($this->iframeUrlQuery) || $this->isEmpty()) {
            return $this;
        }

        $this->iframeUrl = str_replace('?' . $this->iframeUrlQuery, '', $this->iframeUrl);
        $this->_updateIframeQuery();
        return $this;
    }

    /**
     * @inheritDoc
     */
    public function get()
    {
        return !$this->isEmpty() ? str_replace('"', "%22", urldecode($this->iframeUrl)) : null;
    }
}
