<?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\Dialog as DialogCollector;
use idoit\Module\SyneticsFlows\Model\AttributeDataExtractor\ExtractorInterface;
use idoit\Module\SyneticsFlows\Model\Dto\AttributeData;
use isys_application;

class Dialog implements ExtractorInterface
{
    /**
     * @param AbstractCollector $dataCollector
     *
     * @return bool
     */
    public function supports(AbstractCollector $dataCollector): bool
    {
        return $dataCollector instanceof DialogCollector;
    }

    /**
     * @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 (!$this->supports($dataCollector)) {
            return [];
        }

        $data = $dataCollector->collectData($property, true) ?? [];
        $language = isys_application::instance()->container->get('language');

        $data = array_map(function($item) use ($language) {
            $id = (string)$item['id'];
            $title = $language->get($item['title']);
            unset($item['id'], $item['title']);

            return new AttributeData(
                $id,
                $title
            );
        }, $data);

        if ($entryId === null) {
            return $data;
        }

        return array_values(array_filter($data, fn($item) => $item->getId() === $entryId));
    }
}
