<?php

namespace idoit\Module\Console\Steps\Addon;

use idoit\Module\Console\Steps\Message\ErrorLevel;
use idoit\Module\Console\Steps\Message\Message;
use idoit\Module\Console\Steps\Message\Messages;
use idoit\Module\Console\Steps\Step;
use isys_application;
use isys_component_dao_mandator;
use isys_component_database;
use isys_module_manager;
use Symfony\Component\Console\Command\Command;

class AddonUninstall implements Step
{
    private string $id;

    /**
     * @param string $addonIdentifier
     */
    public function __construct(string $addonIdentifier)
    {
        $this->id = $addonIdentifier;
    }

    /**
     * Get name of the step
     *
     * @return string
     */
    public function getName()
    {
        return "Uninstall add-on {$this->id} globally for all tenants";
    }

    /**
     * Process the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function process(Messages $messages)
    {
        try {
            $addonIdentifier = $this->id;
            $baseDb = isys_application::instance()->container->get('database');

            if (!$addonIdentifier) {
                $messages->addMessage(new Message('Add-on identifier is missing', ErrorLevel::ERROR));
                return false;
            }

            $dao = new isys_component_dao_mandator(isys_application::instance()->container->get('database_system'));
            $tenants = $dao->get_mandator(null, 0);

            // Collect tennats
            $tenantDBs = [];
            while ($tenantData = $tenants->get_row()) {
                $db = isys_component_database::factory(
                    'mysql',
                    $tenantData['isys_mandator__db_host'],
                    $tenantData['isys_mandator__db_port'],
                    $tenantData['isys_mandator__db_user'],
                    isys_component_dao_mandator::getPassword($tenantData),
                    $tenantData['isys_mandator__db_name']
                );

                if (!$db->is_connected()) {
                    $messages->addMessage(new Message("Unable to connect to database of tenant {$tenantData['isys_mandator__title']} - SKIP", ErrorLevel::NOTIFICATION));
                    continue;
                }
                $tenantDBs[] = $db;
            }

            // Uninstall add-on
            $manager = new isys_module_manager($baseDb);
            $resultMessages = [];
            $result = $manager->uninstallAddOn($addonIdentifier, $tenantDBs, $resultMessages);

            // Any errors occured?
            if (!$result) {
                $messages->addMessage(new Message(implode(PHP_EOL, $resultMessages), ErrorLevel::ERROR));
                return false;
            }

            // Close tenant DBs
            foreach ($tenantDBs as $tenantDb) {
                $tenantDb->close();
            }
            return true;
        } catch (\Throwable $e) {
            $messages->addMessage(new Message($e->getMessage(), ErrorLevel::FATAL));

            return Command::FAILURE;
        }
    }
}
