<?php

namespace KupShop\AdminBundle\Util\Script;

use KupShop\KupShopBundle\Util\System\BundleFinder;

class ScriptLocator
{
    /**
     * @var BundleFinder
     */
    private $bundleFinder;

    protected bool $isQuiet = false;

    public function __construct(BundleFinder $bundleFinder)
    {
        $this->bundleFinder = $bundleFinder;
    }

    public function setQuiet(bool $isQuiet = true): ScriptLocator
    {
        $this->isQuiet = $isQuiet;

        return $this;
    }

    public function getScripts()
    {
        $scripts = [];

        $scriptFolders = $this->bundleFinder->getExistingBundlesPath('Resources/script');
        $scriptFolders[] = './script';

        foreach ($scriptFolders as $folder) {
            foreach (glob("{$folder}/*.php") as $script) {
                $class = include_once $script;
                $scripts[$script] = [
                    'name' => $class::getName(),
                    'parameters' => $class::getDefaultParameters(),
                    'class' => $class,
                ];
            }
        }

        return $scripts;
    }

    public function runScript($script, $arguments, $class = null)
    {
        if (!isset($class)) {
            $class = include_once $script;
            /** @var Script $script */
            $script = new $class();
        } else {
            $script = new $class();
        }
        $script->setQuiet($this->isQuiet);
        $script->dispatch($arguments);
    }
}
