<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\SelectOptionValue;
use isys_cmdb_dao_category_s_group_type;

class DynamicGroupsDataSource implements DataSource
{
    /**
     * @param isys_cmdb_dao_category_s_group_type $dao
     */
    public function __construct(private isys_cmdb_dao_category_s_group_type $dao)
    {
    }

    /**
     * @param array $parameters
     * @return array|SelectOptionValue[]
     */
    public function getValues(array $parameters): array
    {
        $values = array_map(
            fn (array $group) => new SelectOptionValue($group['id'], $group['title']),
            $this->collectDynamicGroups()
        );

        return array_values($values);
    }

    /**
     * @return array
     */
    private function collectDynamicGroups(): array
    {
        $condition = ' AND isys_cats_group_type_list__type = 1 AND isys_cats_group_type_list__isys_report__id IS NOT NULL ';
        $resource = $this->dao->get_data(null, null, $condition);

        $collectedGroups = [];

        if ($resource->count()) {
            while ($groupRow = $resource->get_row()) {
                $collectedGroups[] = [
                    'title' => $groupRow['isys_obj__title'],
                    'id'    => $groupRow['isys_obj__id'],
                ];
            }
        }

        return $collectedGroups;
    }
}
