<?php

namespace App\Controller;

use App\Form\CityToolType;
use App\Service\OverpassClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/tools')]
class ToolsController extends AbstractController
{
    #[Route('/', name: 'app_tools')]
    public function index(): Response
    {
        return $this->render('tools/index.html.twig', [
        ]);
    }

    #[Route('/city', name: 'app_tools_city')]
    public function city(
        Request $request,
        OverpassClient $overpass,
    ): Response {
        $form = $this->createForm(CityToolType::class, []);
        $form->add('submit', SubmitType::class, ['label' => 'Générer']);

        $form->handleRequest($request);
        if ($form->isSubmitted() and $form->isValid()) {
            $areaId = $form->get('area')->getData();
            $query = sprintf('relation["boundary"="administrative"]["admin_level"="8"]["name"](area:%d);', 3600000000 + $areaId); // Cf. <https://wiki.openstreetmap.org/wiki/Overpass_API/Overpass_QL#By_area_.28area.29>
            $json = $overpass->query($query);

            $response = new StreamedResponse();

            $response->headers->set('Content-Type', 'text/csv');
            $response->headers->set(
                'Content-Disposition',
                HeaderUtils::makeDisposition(
                    HeaderUtils::DISPOSITION_ATTACHMENT,
                    sprintf('cities-in-%d.csv', $areaId)
                )
            );

            $response->setCallback(function () use ($json): void {
                $headings = [
                    'name',
                    'description',
                    'osm',
                    'geojson',
                    'status',
                ];

                $csv = fopen('php://output', 'a');

                fputcsv($csv, $headings);

                $osm = \OSM\OSM::createFromJson($json);

                foreach ($osm->elements as $relation) {
                    $name = $relation->getTagValue('name');

                    $feature = new \GeoJson\Feature\Feature(
                        \OSM\GeoJsonConverter::convertRelationToPolygon($relation),
                        ['name' => $name]
                    );

                    fputcsv($csv, [
                        $name,
                        $name,
                        '',
                        json_encode(new \GeoJson\Feature\FeatureCollection([$feature])),
                        'todo',
                    ]);
                }

                fclose($csv);
            });

            return $response;
        }

        return $this->render('tools/city.html.twig', [
            'form' => $form,
        ]);
    }
}
