<?php

namespace KupShop\FeedGeneratorBundle\XSD;

use KupShop\FeedGeneratorBundle\XSD\Definition\SerializableNode;
use KupShop\FeedGeneratorBundle\XSD\Definition\Type;

class ElementNode extends SerializableNode
{
    private ?Type $selfType = null;
    private ?Type $childType = null;

    public function __construct(\DOMXPath $xpath, \DOMElement $element, \ArrayObject $typeContext)
    {
        parent::__construct($xpath, $element, $typeContext);
        $this->parseTypeDescription($this->element->getAttribute('type'));
    }

    private function parseTypeDescription(string $type): void
    {
        // if is native XSD type, return with the type name
        if (NativeType::isXSDNativeType($type)) {
            $this->selfType = new NativeType($type);
        }
        // if was already registered
        elseif (isset($this->typeContext[$type])) {
            $this->selfType = $this->typeContext[$type];
        }

        foreach ($this->getChildElements() as $child) {
            if (TypeNode::isXSDType($child)) {
                $this->childType = new TypeNode($this->xpathInstance, $child, $this->typeContext);
                break;
            }
        }
    }

    public function serialize(): array
    {
        $elem = [];
        if (!empty($this->selfType)) {
            $elem += $this->selfType->serialize();
        }

        if (!empty($this->childType)) {
            $elem['children'] = $this->childType->serialize();
        }

        return array_merge(
            $elem,              // must be first -> types also have names
            parent::serialize(),
        );
    }

    public function getChildType(): ?Type
    {
        return $this->childType;
    }

    public function getSelfType(): ?Type
    {
        return $this->selfType;
    }
}
