<?php

declare(strict_types=1);

final class QrCodeGetController extends AbstractController
{
    protected string $route = '/api/v1/fingerprint/{fingerprintId}/qr';

    private int $fingerprintId;

    public function __construct(string $url)
    {
        parent::__construct($url);

        $this->fingerprintId = (int)$this->getUrlParamInt('fingerprintId');
    }

    public function handle(): void
    {
        $filename = Setting::PATH_QR_CODES . (string)$this->fingerprintId . '.svg';

        if (!is_file($filename)) {
            $this->response = new ApiJsonResponse(ServerStatus::BAD_REQUEST);
            $this->response->setParameter('success', false);
            $this->response->setMessage(sprintf('No QR code for fingerprint id %d found!', $this->fingerprintId));

            return;
        }

        try {
			$this->response = new ApiSvgResponse();

			$file = @fopen($filename, 'r');
			$this->response->setContent(@fread($file, @filesize($filename)));
			@fclose($file);
		} catch (Throwable $e) {
			$this->response = new ApiJsonResponse(ServerStatus::INTERNAL_ERROR);
			$this->response->setParameter('success', false);
			$this->response->setMessage($e->getMessage());
		}
    }
}