<?php

namespace App\Api\Controller;

use App\Document\Chart;
use App\Api\Model\ChartInput;
use App\Api\Model\ChartOutput;
use Doctrine\ODM\MongoDB\DocumentManager;
use App\Api\Controller\AbstractRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

#[Rest\Route(path: '/api/charts', name: 'api_charts_')]
class ChartRestController extends AbstractRestController
{

    #[Rest\Get('/', name: 'list')]
    public function list(DocumentManager $dm, Request $request) : Response
    {
        $charts = \array_map(fn(Chart $entity) => ChartOutput::fromEntity($entity)->id, iterator_to_array($this->getUser()->getCharts()));
        return $this->respond($charts, Response::HTTP_OK);
    }

    #[Rest\Get('/{id}', name: 'detail')]
    public function detail(DocumentManager $dm, Chart $chart): Response
    {
        $chartDto = ChartOutput::fromEntity($chart);
        return $this->respond( $chartDto, Response::HTTP_OK);
    }

    #[Rest\Post('/insert', name: 'insert')]
    public function insert(DocumentManager $dm, Request $request): Response
    {
        if ($this->getUser() === null)
            throw $this->createAccessDeniedException('Uživatel musí být přihlášen!');

        $data = json_decode($request->getContent());
        $chart = new Chart();
        $chart->setName($data->name);
        $chart->setMetadata($data->metadata);
        $chart->setTable($data->table);
        $this->getUser()->addChart($chart);

        $dm->persist($chart);
        $dm->flush();
        return $this->respond( $chart->getName(), Response::HTTP_OK);
    }

    #[Rest\Post('/{id}/update', name: 'update')]
    public function update(DocumentManager $dm, Request $request, Chart $chart): Response
    {
        if ($chart->getUser() !== $this->getUser())
            throw $this->createAccessDeniedException('Tento graf patří jinému uživateli!');

        $data = json_decode($request->getContent());
        $chart->setName($data->name);
        $chart->setMetadata($data->metadata);
        $chart->setTable($data->table);

        $dm->persist($chart);
        $dm->flush();
        return $this->respond( $chart->getName(), Response::HTTP_OK);
    }

    #[Rest\Delete('/{id}/remove', name:'remove')]
    public function remove(DocumentManager $dm, Request $request, Chart $chart): Response
    {
        if ($chart->getUser() !== $this->getUser())
            throw $this->createAccessDeniedException('Tento graf patří jinému uživateli!');

        $dm->remove($chart);
        $dm->flush();

        return $this->respond( $chart->getName(), Response::HTTP_OK);
    }
}