<?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\Data;

use Magento\Mray\CodeStructuralElement\Php\Reflection\GlobalConstantDeclaration;
use Magento\Mray\Index\Collection\Dictionary;
use Magento\Mray\Index\PhpElementKinds;
use phpDocumentor\Reflection\Type;

class PhpConstantMeta extends DataTransferObject implements GlobalConstantDeclaration
{
    /**
     * @param GlobalConstantDeclaration $d
     * @return static
     */
    public static function createFromObject(GlobalConstantDeclaration $d): self
    {
        $data = [];
        $data['name'] = $d->getName();
        $data['type'] = PhpTypeMeta::createFromObject($d->getType());
        $data['checksum'] = $d->getImplementationChecksum();

        return new static($data);
    }

    /**
     * @return int
     */
    public static function getKind(): int
    {
        return PhpElementKinds::DECLARED_ | PhpElementKinds::CONST_;
    }

    /** @var string  */
    protected $name;
    /** @var PhpTypeMeta|null  */
    protected $type;
    /** @var string|null  */
    protected $checksum;

    /**
     * @param array $packed
     * @param Dictionary $dict
     * @return array
     */
    protected static function unpackData(array $packed, Dictionary $dict): array
    {
        return [
            'name' => $packed[0][1] ?? null,
            'type' => isset($packed[0][2]) ? PhpTypeMeta::unpack($dict->read($packed[2]), $dict): null,
            'checksum' => $packed[2] ?? null,
        ];
    }

    /**
     * @param Dictionary $dict
     * @return array
     */
    protected function packData(Dictionary $dict): array
    {
        return [
            0 => [
                0 => static::getKind(),
                1 => $this->name,
                2 => $dict->write($this->type->pack($dict)),
            ],
            2 => $this->checksum,
        ];
    }

    /**
     * @param mixed $data
     */
    public function __construct($data)
    {
        $this->name = $data['name'] ?? null;
        $this->type = $data['type'] ?? null;
        $this->checksum = $data['checksum'] ?? null;
    }

    /**
     * @return string|null
     */
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @return Type
     */
    public function getType(): Type
    {
        return $this->type->cast();
    }

    /**
     * @return string|null
     */
    public function getImplementationChecksum(): ?string
    {
        return $this->checksum;
    }
}
