<?php



declare(strict_types = 1);

namespace KoolKode\K1;

use Composer\Composer;
use Composer\Factory;
use Composer\EventDispatcher\Event;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\ScriptEvents;

class Plugin implements PluginInterface, EventSubscriberInterface
{
    protected $composer;

    protected $io;

    public static function getSubscribedEvents()
    {
        return [
            ScriptEvents::POST_AUTOLOAD_DUMP => 'updateManifest'
        ];
    }

    public function activate(Composer $composer, IOInterface $io)
    {
        $this->composer = $composer;
        $this->io = $io;
    }

    public function updateManifest(Event $event)
    {
        $file = @\realpath(Factory::getComposerFile());
        
        if ($file === false) {
            return;
        }
        
        if (!\class_exists(ManifestBuilder::class, false)) {
            require_once __DIR__ . '/ManifestBuilder.php';
        }
        
        $builder = new ManifestBuilder($this->composer->getPackage(), $this->composer->getRepositoryManager());
        $builder->updateManifest($file, $this->io);
    }
}
