<?php

namespace idoit\Module\Console\Console\Command\Addon;

use idoit\Component\ConstantManager;
use idoit\Module\Console\Console\Command\AbstractConfigurableCommand;
use idoit\Module\Console\Option\ArrayOption;
use idoit\Module\Console\Option\NumberOption;
use idoit\Module\Console\Option\Option;
use idoit\Module\Console\Option\PasswordOption;
use idoit\Module\Console\Steps\Addon\CleanupAfterBundleInstallation;
use idoit\Module\Console\Steps\Addon\ExtractAddonIdentifierFromPackage;
use idoit\Module\Console\Steps\Addon\InstallAddon;
use idoit\Module\Console\Steps\AuthorisationStep;
use idoit\Module\Console\Steps\CollectionStep;
use idoit\Module\Console\Steps\FileSystem\FileExistsCheck;
use idoit\Module\Console\Steps\FileSystem\Unzip;
use idoit\Module\Console\Steps\Message\ErrorLevel;
use idoit\Module\Console\Steps\Step;
use isys_application;
use isys_component_dao_mandator;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

class InstallAddonCommand extends AbstractConfigurableCommand
{
    /**
     *
     * @throws InvalidArgumentException
     */
    protected function configure()
    {
        global $g_db_system;

        if (!is_array($g_db_system)) {
            die("config.inc.php is not loaded! Please, install the i-doit first!\n");
        }

        $this->setName('addon-install')
            ->setDescription('Install add-on')
            ->setHelp(
                <<<TEXT
This command installs the add-on for i-doit tenants
TEXT
            );

        $this->addValue(new Option('system.user', 'i-doit Admin Username', 'admin', new InputOption('user', 'u', InputOption::VALUE_REQUIRED, 'i-doit Admin username')));
        $this->addValue(new PasswordOption(
            'system.password',
            'i-doit Admin Password',
            null,
            new InputOption('password', 'p', InputOption::VALUE_OPTIONAL, 'i-doit Admin password'),
            false
        ));
        $this->addValue(new Option('addon.zip', 'Path to add-on Zip file', null, new InputOption('zip', 'z', InputOption::VALUE_OPTIONAL, 'Path to add-on Zip file')));
        $this->addValue(new ArrayOption(new Option(
            'addon',
            'Add-on identifier',
            null,
            new InputOption('addon', 'a', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Add-on identifier')
        )));
        $this->addValue(new ArrayOption(new NumberOption(
            'tenant',
            'Tenant id',
            null,
            new InputOption('tenant', 't', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Tenant id')
        )));

        parent::configure();
    }

    /**
     * Create the work
     *
     * @return Step
     */
    protected function createStep()
    {
        $db = isys_application::instance()->container->get('database_system');
        $zip = $this->getValue('addon.zip');
        $addons = $this->getValue('addon');
        $tenantIds = $this->getValue('tenant');
        $tenantDao = isys_component_dao_mandator::instance($db);

        if (empty($tenantIds)) {
            $tenantIds = [];
            $res = $tenantDao->get_mandator();

            while ($tenant = $res->get_row()) {
                $tenantIds[] = $tenant['isys_mandator__id'];
            }
        }

        $tempDirectory = BASE_DIR . 'temp/addon-' . substr(md5(microtime()), 0, 8) . '/';

        $installStep = $zip
            ? new CollectionStep('Install add-on via Zip', [
                new FileExistsCheck($zip, true, ErrorLevel::FATAL),
                new Unzip($zip, $tempDirectory),
                new ExtractAddonIdentifierFromPackage($tempDirectory, function ($packageFile, $addon, $messages) use ($tenantIds, $db, $tempDirectory) {
                    return (new CollectionStep('Install', [
                        new InstallAddon($addon, $tenantIds, $db, $tempDirectory)
                    ]))->process($messages);
                }),
                new CleanupAfterBundleInstallation($tempDirectory)
            ])
            : new CollectionStep('Install add-ons', array_map(function ($addon) use ($db, $tenantIds, $tempDirectory) {
                return new InstallAddon($addon, $tenantIds, $db, $tempDirectory);
            }, $addons));

        return new CollectionStep('Install add-on', [
            new AuthorisationStep($this->getValue('system.user'), $this->getValue('system.password')),
            $installStep
        ]);
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $result = parent::execute($input, $output);

        // Delete cache.
        (new Filesystem())->remove(glob(BASE_DIR . 'temp/*'));

        // Re-Create constant cache.
        /** @var ConstantManager $cm */
        $cm = isys_application::instance()->container->get('constant_manager');
        $cm->createSystemCacheFile();
        $cm->createTenantCacheFile();

        return $result;
    }
}
