<?php

namespace App\Controller;

use App\Api\TTRssClient;
use App\Core\Controller\Site\PageController;
use App\Markdown\Parser\Post as PostParser;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\StlMeshRepositoryQuery;
use App\Entity\StlMesh;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Annotation\Route;

class StlMeshController extends PageController
{
    public function meshes(StlMeshRepositoryQuery $query): Response
    {
        $pager = $query->create()
            ->orderBy('.sortOrder')
            ->paginate(1, 200);

        return $this->defaultRender($this->siteRequest->getPage()->getTemplate(), [
            'pager' => $pager,
        ]);
    }

    /**
     * @Route("/mesh/download/{stlMesh}/{key}", name="mesh_download")
     */
    public function download(StlMesh $stlMesh, int $key): Response
    {
        $file = $stlMesh->getFiles()[--$key] ?? null;

        if (null === $file) {
            throw $this->createNotFoundException();
        }

        $response = new BinaryFileResponse($file['file']);
        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            sprintf('%s.stl', $file['name'])
        );

        return $response;
    }

    /**
     * @Route("/mesh/viewer/{stlMesh}/{key}", name="mesh_viewer")
     */
    public function viewer(StlMesh $stlMesh, int $key): Response
    {
        $file = $stlMesh->getFiles()[--$key] ?? null;

        if (null === $file) {
            throw $this->createNotFoundException();
        }

        if (isset($file['htmlPreviewFile'])) {
            $file['htmlPreviewFile'] = file_get_contents($file['htmlPreviewFile']);
        }

        return $this->render('page/mesh/viewer.html.twig', [
            'mesh' => $stlMesh,
            'file' => $file,
            'key' => $key + 1,
        ]);
    }
}
