<?php

namespace App\Controller;

use App\Enum\ChartEnum;
use App\Utils\ChartUtils;
use App\Utils\CustomEntityManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;

class ChartsController extends AbstractController
{
    private $em;
    private $session;
    private $security;
    private $chartUtils;

    public function __construct(SessionInterface $session, CustomEntityManager $em, Security $security, ChartUtils $chartUtils)
    {
        $this->em = $em;
        $this->session = $session;
        $this->security = $security;
        $this->chartUtils = $chartUtils;
    }

    /**
     * @Route("/admin/charts/content/load", name="loadChartContent")
     * @Method({"GET"})
     * @IsGranted("ROLE_ADMIN")
     */
    public function loadChartHtml(Request $request): Response
    {
        $chartHtml = $this->renderView('@kohinos/block/block_charts_content.html.twig', []);

        return new JsonResponse([
            'success' => true,
            'html' => $chartHtml
        ]);
    }

    /**
     * @Route("/admin/charts/load", name="getChartHtml")
     * @Method({"GET"})
     * @IsGranted("ROLE_ADMIN")
     */
    public function loadChart(Request $request): Response
    {
        if (!$request->isXmlHttpRequest()) {
            return new Response('', Response::HTTP_BAD_REQUEST);
        }
        $type = '';
        if (null != $request->get('type')) {
            $type = $request->get('type');
        }
        if (!in_array($type, ChartEnum::getAvailableTypes())) {
            return new JsonResponse([
                'success' => false,
                'error' => 'Type de graphique invalide !'
            ]);
        }
        $params = [];
        if (null != $request->get('params')) {
            if (!is_array($request->get('params'))) {
                return new JsonResponse([
                    'success' => false,
                    'error' => 'Paramètres du graphique invalide !'
                ]);
            }
            $params = $request->get('params');
        }
        $title = '';
        if (null != $request->get('title')) {
            $title = $request->get('title');
        }

        $chartHtml = $this->renderView('@kohinos/charts/block.html.twig', [
            'title' => $title,
            'chart' => $this->chartUtils->getMlcChart($type, $params)
        ]);

        return new JsonResponse([
            'success' => true,
            'html' => $chartHtml
        ]);
    }
}
