<?php

namespace idoit\Module\Pro\Controller\CmdbExplorer;

use isys_application;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
 * Graph controller for CMDB-Explorer.
 *
 * @package   Modules
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class Graph
{
    private \isys_component_database $database;
    private \isys_component_template_language_manager $language;
    private \isys_cmdb_dao $cmdbDao;

    public function __construct()
    {
        $this->database = isys_application::instance()->container->get('database');
        $this->language = isys_application::instance()->container->get('language');
        $this->cmdbDao = isys_application::instance()->container->get('cmdb_dao');
    }

    /**
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function loadData(Request $request): JsonResponse
    {
        try {
            \isys_module_cmdb::getAuth()->check(\isys_auth::VIEW, 'EXPLORER');

            $objectId = (int)$request->query->get('object');
            $filter = (int)$request->query->get('filter');
            $profile = (int)$request->query->get('profile');

            $model = new \isys_visualization_graph_model($this->database);

            // @see  ID-7223  Check if the object exists, before processing the rest.
            if (!$this->cmdbDao->obj_exists($objectId)) {
                throw new \Exception($this->language->get('LC__CMDB__OBJECT_DOES_NOT_EXIST', $objectId));
            }

            $responseData = [
                'success' => true,
                'data'    => [
                    'nodes'   => array_values($model->recursion_run($objectId, $filter, $profile)->toArray()),
                    'profile' => \isys_visualization_profile_model::instance($this->database)->get_profile_config($profile)
                ],
                'message' => ''
            ];

            return new JsonResponse($responseData);
        } catch (Throwable $e) {
            return new JsonResponse([
                'success' => false,
                'data' => null,
                'message' => $e->getMessage()
            ]);
        }
    }
}
