<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\DataSource\JDisc;

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\DataSource\DataSource;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\SelectOptionValue;
use idoit\Module\SyneticsFlows\Helper\JDiscHelper;
use isys_helper_crypt;
use isys_jdisc_dao_discovery;

class JDiscDiscoveryJobDataSource implements DataSource
{
    /**
     * @param array $parameters
     * @return array|SelectOptionValue[]
     * @throws \isys_exception_general
     */
    public function getValues(array $parameters): array
    {
        if (empty($parameters['server'])) {
            return [];
        }

        $server = JDiscHelper::getClassName()::factory()->get_jdisc_discovery_data($parameters['server'], true)->get_row();
        [
            'isys_jdisc_db__host' => $host,
            'isys_jdisc_db__discovery_port' => $port,
            'isys_jdisc_db__discovery_protocol' => $protocol,
            'isys_jdisc_db__discovery_username' => $username,
        ] = $server;

        $password = isys_helper_crypt::decrypt($server['isys_jdisc_db__discovery_password']);
        $discoveryObj = isys_jdisc_dao_discovery::get_instance($parameters['server']);
        $discoveryObj->connect($host, $username, $password, $port, $protocol);
        $values = array_map(
            fn (mixed $data) => new SelectOptionValue($data['name'], $data['name']),
            $discoveryObj->get_discovery_jobs(),
        );

        $discoveryObj->disconnect();

        return array_values($values);
    }
}
