<?php

namespace idoit\Module\Pro\Algorithm\Formatter;

use isys_cmdb_dao;
use isys_helper_color;
use isys_tree_node_explorer;

/**
 * Class DefaultFormatter
 *
 * @package idoit\Module\Pro\Algorithm\Formatter
 */
class DefaultFormatter extends AbstractFormatter
{
    /**
     * @param  int   $objectId
     * @param  array $data
     * @param  bool  $doubling
     *
     * @return isys_tree_node_explorer
     * @throws \isys_exception_database
     */
    public function formatNode(int $objectId, array $data, bool $doubling): isys_tree_node_explorer
    {
        // This should not happen during the algorithm, but will happen for the root node.
        if (count($data) === 0) {
            $dao = isys_cmdb_dao::instance($this->database);

            $query = "SELECT 
                isys_obj__title AS objectTitle, 
                isys_obj_type__id AS objectTypeId, 
                isys_obj_type__color AS objectTypeColor, 
                CASE isys_obj_type__const
                    WHEN 'C__OBJTYPE__RELATION' THEN isys_relation_type__title
                    ELSE isys_obj_type__title
                END AS objectTypeTitle
                FROM isys_obj
                LEFT JOIN isys_obj_type ON isys_obj_type__id = isys_obj__isys_obj_type__id
                LEFT JOIN isys_cmdb_status ON isys_cmdb_status__id = isys_obj__isys_cmdb_status__id
                LEFT JOIN isys_catg_relation_list ON isys_catg_relation_list__isys_obj__id = isys_obj__id
                LEFT JOIN isys_relation_type ON isys_relation_type__id = isys_catg_relation_list__isys_relation_type__id
                WHERE isys_obj__id = {$objectId};";

            // Load row_data in case it is not present.
            $data = $dao->retrieve($query)->get_row();
        }

        return new isys_tree_node_explorer([
            'id'       => $objectId,
            'name'     => trim($data['objectTitle']),
            'children' => [],
            'data'     => [
                'doubling'        => $doubling,
                'obj_id'          => $objectId,
                'obj_title'       => trim($data['objectTitle']),
                'obj_type_id'     => $data['objectTypeId'],
                'obj_type_title'  => $this->language->get($data['objectTypeTitle']),
                'obj_type_color'  => isys_helper_color::unifyHexColor($data['objectTypeColor']),
                'relation_obj_id' => $data['relationObjectId'] ?: null
            ]
        ]);
    }
}
