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

use Magento\Mray\CodeStructuralElement\Php\Reflection\Context\StructuralElementDeclarations;
use Magento\Mray\Index\MagentoApiIndexAdapter;
use Magento\Mray\Index\Traverser\PhpCodeUsageFilter\ExtensionCodeUsageFilter;
use Magento\Mray\MagentoApiIndex\Index\Version;
use Magento\Mray\Package\AbstractTree\Node\Node;
use Magento\Mray\Index\Scanner\Tuner;
use Magento\Mray\Index\Traverser;

class ExtensionIndex
{
    /**
     * @var Node[]
     */
    private $idx;

    /**
     * @param string $path
     * @param Version|null $version
     */
    public function __construct(string $path, ?Version $version = null)
    {
        $phpElementsRegistry = new StructuralElementDeclarations();
        if ($version) {
            $phpElementsRegistry->withKnowledge(new MagentoApiIndexAdapter($version));
        }

        $idx = new MagentoIndexEngine(
            [
                new Tuner\MagentoComposerDistribution(),
                new Tuner\PackagePathAttributeSetter(),
                new Tuner\MagentoPhpCodeNodeSetter(),
                new Tuner\PhpCodeDeclaresAttributeSetter($phpElementsRegistry),
            ],
            [
                new Traverser\PhpCodeRuntimeTypesEstimation($phpElementsRegistry),
                new Traverser\PhpCodeUsageDiscovery(
                    $phpElementsRegistry,
                    new ExtensionCodeUsageFilter($phpElementsRegistry)
                )
            ]
        );

        $this->idx = $idx->index($path);
    }

    /**
     * @return array
     */
    public function getCustomizations(): array
    {
        $formatter = new Traverser\Formatter();
        (new Traverser\VisitingTraverser([$formatter]))->traverse($this->idx);
        return $formatter->getOutput();
    }
}
