<?php

namespace Application\Service\Extension\Xml;

use Application\Service\Extension\Helper\StringHelper;
use DOMDocument;
use DOMElement;
use DOMException;

/**
 * 同步用的xml类
 */
class XmlBuilder
{
    /**
     * @var string XML version.
     */
    public string $version = '1.0';

    /**
     * @var string|null the XML encoding.
     */
    public string $encoding = 'UTF-8';

    /**
     * The URI of the namespace.
     * @var string
     */
    public string $namespaceURI = 'http://www.cdisc.org/ns/odm/v1.3';

    /**
     * The qualified name of the element, as prefix:tagname.
     * @var string
     */
    public string $qualifiedName = 'ODM';

    /**
     * Root tag attributes.
     * @var array|string[]
     */
    public array $rootTagAttributes = [
        'xmlns:HLT' => 'https://www.yiducloud.com.cn/odm',
        'FileType' => 'Transactional',
        'Granularity' => 'All',
        'AsOfDateTime' => '0001-01-01T00:00:00',
        'ODMVersion' => '1.3',
    ];

    /**
     * 属性分隔符.
     * 默认以空格符分割.
     * @var string
     */
    public string $attributeSeparator = ' ';

    /**
     * @var string the name of the elements that represent the array elements with numeric keys.
     */
    public $itemTag = 'item';

    /**
     * @var bool whether to interpret objects implementing the [[\Traversable]] interface as arrays.
     * Defaults to `true`.
     * @since 2.0.7
     */
    public $useTraversableAsArray = true;
    /**
     * @var bool if object class names should be used as tag names
     * @since 2.0.11
     */
    public $useObjectTags = true;
    /**
     * @var bool if true, converts object tags to lowercase, `$useObjectTags` must be enabled
     * @since 2.0.43
     */
    public $objectTagToLowercase = false;

    /**
     * @var DOMDocument the XML document, serves as the root of the document tree
     * @since 2.0.43
     */
    protected $dom;


    public function build(array $data)
    {
        $charset = $this->encoding === null ? false : $this->encoding;

        if ($data) {
            $this->dom = new DOMDocument($this->version, $charset);
            $root = $this->getRootElement();
            $this->dom->appendChild($root);
            $this->buildXml($root, $data);

            $response = $this->dom->saveXML();
        }

        return $response;
    }

    /**
     * 生成Root tag.
     * @return DOMElement
     */
    protected function getRootElement(): DOMElement
    {
        $root = $this->dom->createElementNS($this->namespaceURI, $this->qualifiedName);

        date_default_timezone_set('PRC');

        $this->rootTagAttributes['CreationDateTime'] = date(DATE_ATOM, mktime(date('H'), date('i'), date('s'), date('m'), date('d'), date('Y')));

        $this->rootTagAttributes['FileOID'] = StringHelper::generateUuid();

        if ($this->rootTagAttributes) {
            $this->setAttributes($root, $this->rootTagAttributes);
        }

        return $root;
    }

    /**
     * 设置tag 属性.
     * @param DOMElement $dom
     * @param array $attributes
     */
    protected function setAttributes(DOMElement &$dom, array $attributes)
    {
        foreach ($attributes as $key => $attribute) {
            $dom->setAttribute($key, $attribute);
        }
    }

    /**
     * Formats the specified response.
     *
     */
    public function format($response)
    {
        if ($response !== null) {
            $this->dom = new DOMDocument($this->version, $this->encoding);
            $this->buildXml($this->dom, $response);
            $response = $this->dom->saveXML();
        }

        return $response;
    }

    /**
     * Recursively adds data to XML document.
     *
     * @param DOMElement|DOMDocument $element current element
     * @param mixed $data content of the current element
     */
    protected function buildXml($element, $data)
    {
        if (is_array($data)) {
            foreach ($data as $name => $value) {
                [$elementName, $elAttrs] = $this->getElementAttribute($name);

                if (is_int($elementName) && is_object($value)) {
                    $this->buildXml($element, $value);
                } elseif (is_array($value) || is_object($value)) {
                    $child = $this->dom->createElement($this->getValidXmlElementName($elementName));
                    foreach ($elAttrs as $k => $v) {
                        $child->setAttribute($k, $v);
                    }
                    $element->appendChild($child);
                    $this->buildXml($child, $value);
                } else {
                    $child = $this->dom->createElement($this->getValidXmlElementName($elementName));
                    $child->appendChild($this->dom->createTextNode($this->formatScalarValue($value)));
                    $element->appendChild($child);
                }
            }
        } elseif (is_object($data)) {
            if ($this->useObjectTags) {
                $name = StringHelper::basename(get_class($data));
                if ($this->objectTagToLowercase) {
                    $name = strtolower($name);
                }
                $child = $this->dom->createElement($name);
                $element->appendChild($child);
            } else {
                $child = $element;
            }

            $array = [];
            foreach ($data as $name => $value) {
                $array[$name] = $value;
            }
            $this->buildXml($child, $array);
        } else {
            $element->appendChild($this->dom->createTextNode($this->formatScalarValue($data)));
        }
    }

    private function getElementAttribute($name)
    {
        preg_match_all('/{{(.*?)}}/', $name, $mat, PREG_SET_ORDER);

        $name = explode($this->attributeSeparator, trim($name));

        $elementName = array_shift($name);

        if (!$name) {
            return [$elementName, []];
        }

        $attr = [];

        foreach ($mat as $item) {
            $payload = explode(':=', $item[1]);
            if (count($payload) == 2) {
                $attr[$payload[0]] = $payload[1];
            }
        }

        return [$elementName, $attr];
    }

    /**
     * Formats scalar value to use in XML text node.
     *
     * @param int|string|bool|float $value a scalar value.
     * @return string string representation of the value.
     * @since 2.0.11
     */
    protected function formatScalarValue($value)
    {
        if ($value === true) {
            return 'true';
        }
        if ($value === false) {
            return 'false';
        }
        if (is_float($value)) {
            return StringHelper::floatToString($value);
        }
        return (string) $value;
    }

    /**
     * Returns element name ready to be used in DOMElement if
     * name is not empty, is not int and is valid.
     *
     * Falls back to [[itemTag]] otherwise.
     *
     * @param mixed $name the original name
     * @return string
     * @since 2.0.12
     */
    protected function getValidXmlElementName($name, $value = '')
    {
        if (empty($name) || is_int($name) || !$this->isValidXmlName($name)) {
            return $value ?: $this->itemTag;
        }

        return $name;
    }

    /**
     * Checks if name is valid to be used in XML.
     *
     * @param mixed $name the name to test
     * @return bool
     * @see https://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943
     * @since 2.0.12
     */
    protected function isValidXmlName($name)
    {
        try {
            return $this->dom->createElement($name) !== false;
        } catch (DOMException $e) {
            return false;
        }
    }
}
