<?php

namespace idoit\Module\Pro\Controller\CmdbExplorer;

use GuzzleHttp\Psr7\MimeType;
use idoit\Module\Pro\Export\GraphML;
use isys_application;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

/**
 * Export controller for CMDB-Explorer.
 *
 * @package   Modules
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class Export
{
    /**
     * @param Request $request
     *
     * @return Response
     */
    public function graphml(Request $request): Response
    {
        try {
            set_time_limit(0);

            $get = $request->query->all();

            $graphmlExport = new GraphML(
                isys_application::instance()->container->get('cmdb_dao'),
                isys_application::instance()->container->get('language'),
                $get['type'],
                (int)$get['object'],
                (int)$get['profile'],
                (int)$get['service-filter'],
                array_map(fn ($object) => $object, explode(',', $get['visible-objects']))
            );

            $mimetype = MimeType::fromExtension('xml') ?? 'application/octet-stream';
            $disposition = HeaderUtils::makeDisposition(
                HeaderUtils::DISPOSITION_ATTACHMENT,
                "cmdb-export_" . date('Y-m-d') . ".graphml"
            );

            return new Response(
                $graphmlExport->export(),
                Response::HTTP_OK,
                ['Content-Type' => $mimetype, 'Content-Disposition' => $disposition]
            );
        } catch (Throwable $e) {
            return new Response($e->getMessage());
        }
    }
}
