<?php

namespace idoit\Module\Console\Steps\Addon;

use idoit\Module\Console\Steps\CollectionStep;
use idoit\Module\Console\Steps\Message\Messages;
use idoit\Module\Console\Steps\Step;
use idoit\Module\Console\Steps\Undoable;
use isys_component_database;

class InstallAddon implements Step, Undoable
{
    /**
     * @var CollectionStep
     */
    private $step;

    /**
     * InstallAddon constructor.
     *
     * @param string                  $addon
     * @param array                   $tenantIds
     * @param isys_component_database $db
     */
    public function __construct(string $addon, array $tenantIds, isys_component_database $db, ?string $fromTempDirectory = null)
    {
        $this->step = new CollectionStep('Install Add-on ' . $addon, [
            new CollectionStep('Check requirements of Add-on ' . $addon, []),
            // Removed the "check for install script" check because this is handled in 'AddonInstall' already.
            new CollectionStep('Install Add-on ' . $addon . ' into tenants', array_map(function ($tenantId) use ($db, $addon, $fromTempDirectory) {
                return new AddonInstall($addon, $tenantId, $db, $fromTempDirectory);
            }, $tenantIds))
        ]);
    }

    /**
     * Get name of the step
     *
     * @return string
     */
    public function getName()
    {
        return $this->step->getName();
    }

    /**
     * Process the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function process(Messages $messages)
    {
        return $this->step->process($messages);
    }

    /**
     * Undo the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function undo(Messages $messages)
    {
        return $this->step->undo($messages);
    }
}
