<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Model\AttributeDataExtractor\Type;

use idoit\Component\Property\Property;
use idoit\Module\Cmdb\Component\AttributeDataCollector\CollectorTypes\AbstractCollector;
use idoit\Module\Cmdb\Component\AttributeDataCollector\CollectorTypes\BrowserObject as BrowserObjectCollector;
use idoit\Module\SyneticsFlows\Model\AttributeDataExtractor\ExtractorInterface;
use idoit\Module\SyneticsFlows\Model\Dto\AttributeData;
use idoit\Module\SyneticsFlows\Model\Dto\Category;
use idoit\Module\SyneticsFlows\Model\Dto\CiObject;
use idoit\Module\SyneticsFlows\Model\Dto\ObjectAttributeData;
use isys_cmdb_dao;

class BrowserObject implements ExtractorInterface
{
    private const ID_FIELD = 0;
    private const TITLE_FIELD = 1;
    private const TYPE_FIELD = 2;

    /**
     * @param AbstractCollector $dataCollector
     *
     * @return bool
     */
    public function supports(AbstractCollector $dataCollector): bool
    {
        return $dataCollector instanceof BrowserObjectCollector;
    }

    /**
     * @param Property          $property
     * @param AbstractCollector $dataCollector
     * @param string|null       $entryId
     *
     * @return array
     * @throws \idoit\Module\Cmdb\Component\AttributeDataCollector\Exceptions\NoProperCollectorTypeFoundException
     */
    public function extract(Property $property, AbstractCollector $dataCollector, ?string $entryId = null): array
    {
        if (!$dataCollector instanceof BrowserObjectCollector) {
            return [];
        }

        $dataCollector->displayAttributeCategories(false);
        $dataCollector->overwriteAttributeConfiguration([]);
        $dataCollector->setReturnAsArray(false);

        $result = $dataCollector->collectData($property, false);
        $resource = $result['data'];
        if (!$resource instanceof \isys_component_dao_result) {
            return [];
        }

        $dao = isys_cmdb_dao::instance(\isys_application::instance()->container->get('database'));
        $query = str_replace(["obj_main.isys_obj__id AS '__id__'", "GROUP BY obj_main.isys_obj__id"], ['*', ''], $resource->get_query());
        $data = [];

        if ($entryId !== null) {
            $query .= ' AND obj_main.isys_obj__id = ' . $dao->convert_sql_id($entryId);
        }

        $result = $dao->retrieve($query);

        while($row = $result->get_row()) {
            $data[] = new ObjectAttributeData(
                $row['isys_obj__id'],
                $row['isys_obj__title'],
                $row['isys_obj__isys_obj_type__id'],
                $row['isys_obj__status']
            );
        }

        return $data;
    }
}
