<?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;

class isys_cmdb_dao_category_g_location extends AbstractCategorySource
{
    public function retrieveData(Config $config)
    {
        if (!isys_tenantsettings::get('search.index.location_paths', false)) {
            return [];
        }

        /**
         * @var $dao \isys_cmdb_dao_category_g_location
         */
        $dao = $this->categoryDao;

        $locations = $dao->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();
        $locationPaths = [];

        foreach ($locations as $location) {
            $query = $dao::build_location_path_query(
                isys_tenantsettings::get('cmdb.limits.location-path', 5),
                'WHERE main.isys_catg_location_list__isys_obj__id = ' . $location['isys_catg_location_list__isys_obj__id'],
                true
            );

            $locationPath = $dao->get_database_component()->retrieveArrayFromResource(
                $dao->get_database_component()->query($query)
            );

            if (isset($locationPath[0]['title']) && !empty($locationPath[0]['title'])) {
                $locationPaths[$location['isys_catg_location_list__isys_obj__id']] = [
                    'objectId' => $location['isys_catg_location_list__isys_obj__id'],
                    'categoryEntryId' => $location['isys_catg_location_list__id'],
                    'objectType' => $location['isys_obj__isys_obj_type__id'],
                    'locationPath' => $locationPath[0]['title']
                ];
            }
        }

        return $locationPaths;
    }

    public function mapDataToDocuments(array $data)
    {
        $documents = [];

        foreach ($data as $set) {
            $document = new Document();
            $document->setVersion(SearchEngine::VERSION);
            $document->setType('cmdb');
            $document->setKey(sprintf('%s.%s.%s.%s.%s', $set['objectType'], $set['objectId'], $this->categoryDao->get_category(), $set['categoryEntryId'], 'location_path'));
            $document->setReference($set['objectId']);
            $document->setValue($set['locationPath']);

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

        return $documents;
    }
}
