<?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;

		$filename = $this->getFilePath();

		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 delete(): void
	{
		$filepath = $this->getFilePath();

		if (!is_file($filepath)) {
			throw new QrCodeException(sprintf('Qr code file %s not found!', $filepath));
		}

		if (!unlink($filepath)) {
			throw new QrCodeException('Couldn\'t delete %s!', $filepath);
		}
	}

	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;
	}

	public function hasFile(): bool
	{
		return is_file($this->getFilePath());
	}

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

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

	private function getFilePath(): string
	{
		$path = substr(Setting::PATH_QR_CODES, -1) === '/'
			? Setting::PATH_QR_CODES
			: Setting::PATH_QR_CODES . '/';

		return $path . $this->fingerprintId . '.svg';
	}
}