<?php

/**
 * i-doit
 *
 * Global visualization model.
 *
 * @package     modules
 * @subpackage  pro
 * @author      Leonard Fischer <lfischer@i-doit.com>
 * @version     1.0
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @since       i-doit 1.5.0
 */
class isys_visualization_model extends isys_itservice_dao_algorithm
{
    /**
     * Method for loading the it-service by a given ID.
     *
     * @param   integer $p_filter
     *
     * @return  array
     */
    public function load_service_filter($p_filter)
    {
        $l_filter = [];

        // Prepare the filters.
        if ($p_filter > 0) {
            $l_filter = isys_itservice_dao_filter_config::instance($this->m_db)
                ->get_data($p_filter);

            $l_filter = $l_filter['formatted__data'];
        }

        if (empty($l_filter['level'])) {
            // @see  ID-8807  Limit the recursion run to something low, so we don't run into memory issues.
            $l_filter['level'] = 2;

            // Also notify the user.
            $limitMessage = isys_application::instance()->container->get('language')->get('LC__VISUALIZATION__LEVEL_LIMITER');
            isys_notify::info($limitMessage, ['sticky' => true]);
        }

        return $l_filter;
    }

    /**
     * Method for retrieving the infobox data.
     *
     * @param   integer $p_obj
     * @param   integer $p_profile_id
     * @param   integer $p_relation_obj
     *
     * @return  array
     * @throws  isys_exception_general
     */
    public function load_object_infobox_data($p_obj, $p_profile_id, $p_relation_obj = null)
    {
        $language = isys_application::instance()->container->get('language');

        $l_relation_row = [];

        /* @var  isys_cmdb_dao $l_dao_cmdb */
        $l_dao_cmdb = isys_cmdb_dao::instance($this->m_db);

        $l_object_data = $l_dao_cmdb->get_object_by_id($p_obj)
            ->get_row();

        $l_dynamic_data = [];

        if ($p_profile_id > 0) {
            try {
                $l_profile = isys_visualization_profile_model::instance($this->m_db)
                    ->get_profile($p_profile_id)
                    ->get_row_value('isys_visualization_profile__obj_info_config');

                if (isys_format_json::is_json($l_profile)) {
                    $l_profile = isys_format_json::decode($l_profile);

                    if (!empty($l_profile['query'])) {
                        $l_row = $this->retrieve(sprintf($l_profile['query'], $this->convert_sql_id($p_obj)))
                            ->get_row();

                        foreach ($l_row as $l_key => $l_value) {
                            $l_key = trim($l_key);

                            if (str_starts_with($l_key, 'isys_cmdb_dao_category_')) {
                                $l_arr = explode('::', $l_key);

                                if (class_exists($l_arr[0])) {
                                    $l_cat_dao = call_user_func([
                                        $l_arr[0],
                                        'instance'
                                    ], $this->m_db);

                                    if ($l_value !== null) {
                                        $l_callback_row[$l_arr[2]] = $l_value;

                                        $l_dynamic_data[] = [
                                            $l_arr[3],
                                            call_user_func([
                                                $l_cat_dao,
                                                $l_arr[1]
                                            ], $l_callback_row)
                                        ];
                                    } else {
                                        $l_dynamic_data[] = [
                                            $l_arr[3],
                                            ''
                                        ];
                                    }
                                }

                                continue;
                            }

                            if (str_starts_with($l_key, '__')) {
                                continue;
                            }

                            $l_lc_key = strstr($l_key, '###', true);

                            if ($l_lc_key === false) {
                                $l_lc_key = $l_key;
                            }

                            if (str_contains($l_lc_key, '#')) {
                                $l_key_parts = array_map(fn (string $part) => $language->get($part), explode('#', $l_lc_key));

                                $l_format = '%s';

                                if (count($l_key_parts) == 3) {
                                    $l_format = '%s (%s -> %s)';
                                } elseif (count($l_key_parts) == 2) {
                                    $l_format = '%s (%s)';
                                }

                                $l_lc_key = vsprintf($l_format, $l_key_parts);
                            } else {
                                $l_lc_key = $language->get($l_lc_key);
                            }

                            $keyParts = explode('::', $l_lc_key);
                            if ($keyParts[0]==='locales') {
                                $l_lc_key = $language->get_in_text(implode('::', array_slice($keyParts, 2)));
                            }

                            $l_dynamic_data[] = [
                                $l_lc_key,
                                $l_value
                            ];
                        }
                    }
                }
            } catch (Exception $e) {
                $l_dynamic_data = $e;
            }
        }

        if ($p_relation_obj > 0) {
            $l_relation_row = isys_cmdb_dao_category_s_relation_details::instance($this->m_db)
                ->get_data(null, $p_relation_obj)
                ->get_row();
        }

        $routeGenerator = isys_application::instance()->container->get('route_generator');

        // @see ID-11875 Translate via 'get_in_text' in case of concatenated strings.
        if (is_array($l_dynamic_data)) {
            $l_dynamic_data = array_map(
                fn ($set) => [$language->get_in_text($set[0]), $language->get_in_text($set[1])],
                $l_dynamic_data,
            );
        }

        return [
            'image'             => $routeGenerator->generate('cmdb.object.image', ['objectId' => (int)$l_object_data['isys_obj__id']]),
            'obj_id'            => $l_object_data['isys_obj__id'],
            'obj_title'         => $l_object_data['isys_obj__title'],
            'obj_type_id'       => $l_object_data['isys_obj_type__id'],
            'obj_type_title'    => $language->get($l_object_data['isys_obj_type__title']),
            'obj_type_icon'     => $routeGenerator->generate('cmdb.object-type.icon', ['objectTypeId' => (int)$l_object_data['isys_obj_type__id']]),
            'obj_type_color'    => '#' . $l_object_data['isys_obj_type__color'],
            'cmdb_status_title' => $language->get($l_object_data['isys_cmdb_status__title']),
            'cmdb_status_color' => '#' . $l_object_data['isys_cmdb_status__color'],
            'dynamic_data'      => $l_dynamic_data,
            'relation_type'     => isset($l_relation_row['isys_relation_type__title']) ? $language->get($l_relation_row['isys_relation_type__title']) : null
        ];
    }
}
