<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\Index\Collection;

use Magento\Mray\Index\Data\MagentoApiDeclaration;
use Magento\Mray\Index\Data\PhpFqsenMeta;

class MagentoApi implements DataCollection
{
    /** @var Dictionary  */
    private $dictionary;
    /** @var array  */
    private $data = [];

    /**
     * @param Dictionary|null $dictionary
     */
    public function __construct(?Dictionary $dictionary = null)
    {
        $this->dictionary = $dictionary ?? new Dictionary();
    }

    /**
     * @param string $fqsen
     * @param MagentoApiDeclaration $declaration
     */
    public function register(string $fqsen, MagentoApiDeclaration $declaration): void
    {
        $fqsenRef = $this->dictionary->write(
            (new PhpFqsenMeta($fqsen))->pack($this->dictionary)
        );
        $this->data[$fqsenRef] = $this->dictionary->write(
            $declaration->pack($this->dictionary)
        );
    }

    /**
     * @param string $fqsen
     */
    public function registerNonApi(string $fqsen)
    {
        $fqsenRef = $this->dictionary->write(
            (new PhpFqsenMeta($fqsen))->pack($this->dictionary)
        );
        $this->data[$fqsenRef] = 0;
    }

    /**
     * @inheritDoc
     */
    public function exportData(): array
    {
        return $this->data;
    }

    /**
     * @param array $data
     */
    public function importData(array $data): void
    {
        foreach ($data as $fqsenRef => $declarationRef) {
            $this->data[$fqsenRef] = $declarationRef;
        }
    }
}
