<?php

declare(strict_types=1);

final class QrCode
{
    private int $fingerprintId;
    private string $fingerprint;
    private string $temporaryFilename;

    public function __construct(int $fingerprintId, string $fingerprint)
    {
        $this->fingerprintId = $fingerprintId;
        $this->fingerprint = $fingerprint;
    }

    public function save(): void
    {
        if (!is_file($this->temporaryFilename)) {
            throw new QrCodeException(
                sprintf('Temporary QR file %s couldn\'t be found!', $this->temporaryFilename)
            );
        }

        $returnCode = 0;

        $path = substr(Setting::PATH_QR_CODES, -1) === '/'
            ? Setting::PATH_QR_CODES
            : Setting::PATH_QR_CODES . '/';

        $filename = $path . $this->fingerprintId . '.svg';

        passthru(
            sprintf('mv %s %s', $this->temporaryFilename, $filename),
            $returnCode
        );

        if ($returnCode !== 0 || !is_file($filename)) {
            throw new QrCodeException(
                sprintf('QR code for fingerprint %d couldn\'t be created!', $this->fingerprintId)
            );
        }
    }

    public function generate(): bool
    {
        $returnCode = 0;

        $path = substr(Setting::PATH_TMP, -1) === '/' ? Setting::PATH_TMP : Setting::PATH_TMP . '/';

        $this->temporaryFilename = $path . $this->generateTemporaryFilename() . '.svg';

        passthru(
            sprintf('qrencode -o %s -t SVG "%s"', $this->temporaryFilename, $this->fingerprint),
            $returnCode
        );

        return !(bool)$returnCode;
    }

    private function generateTemporaryFilename(): string
    {
        $hash = hash('md5', (new DateTime())->format('U') . $this->fingerprint);

        return sprintf('%s.svg', $hash);
    }
}