<?php

namespace idoit\Module\Cmdb\Search\Index\Data\Source\Category;

use idoit\Module\Search\Index\Data\Source\Config;
use idoit\Module\Search\Index\Document;
use idoit\Module\Search\Index\Engine\SearchEngine;
use isys_tenantsettings;
use Symfony\Component\EventDispatcher\GenericEvent;

class isys_cmdb_dao_category_g_model extends AbstractCategorySource
{
    public function retrieveData(Config $config)
    {
        $data = $this->categoryDao->get_data(
            null,
            ($config->hasObjectIds() ? $config->getObjectIds() : null),
            '',
            null,
            (!isys_tenantsettings::get('search.index.include_archived_deleted_objects', false) ? C__RECORD_STATUS__NORMAL : null)
        )->__as_array();

        $this->eventDispatcher->dispatch('index.data.raw.progress.retrieve', new GenericEvent($this, [
            'count'   => count($data),
            'context' => $this->categoryDao->get_category_const()
        ]));

        return $data;
    }

    /**
     * @inheritdoc
     */
    public function mapDataToDocuments(array $data)
    {
        $this->eventDispatcher->dispatch('index.data.document.mapping.progress.start', new GenericEvent($this, [
            'count'        => count($data),
            'countOverall' => count($data) * 2,
            'context'      => $this->categoryDao->get_category_const()
        ]));

        $documents = [];

        foreach ($data as $set) {
            $steps = 2;

            $document = new Document();
            $document->setVersion(SearchEngine::VERSION);
            $document->setType('cmdb');
            $document->setKey(sprintf('%s.%s.%s.%s.%s', $set['isys_obj__isys_obj_type__id'], $set['isys_obj__id'], $this->categoryDao->get_category(), $set['isys_catg_model_list__id'], 'manufacturer'));
            $document->setReference($set['isys_obj__id']);
            $document->setValue($set['isys_model_manufacturer__title']);

            $documents[$document->getKey()] = $document;

            $document = new Document();
            $document->setVersion(SearchEngine::VERSION);
            $document->setType('cmdb');
            $document->setKey(sprintf('%s.%s.%s.%s.%s', $set['isys_obj__isys_obj_type__id'], $set['isys_obj__id'], $this->categoryDao->get_category(), $set['isys_catg_model_list__id'], 'title'));
            $document->setReference($set['isys_obj__id']);
            $document->setValue($set['isys_model_title__title']);

            $documents[$document->getKey()] = $document;

            $this->eventDispatcher->dispatch('index.data.document.mapping.progress.advance', new GenericEvent($this, [
                'steps' => $steps
            ]));
        }

        $this->eventDispatcher->dispatch('index.data.document.mapping.progress.finish', new GenericEvent($this));

        return $documents;
    }
}
