<?php

declare(strict_types=1);

namespace Dealerdirect\Agreements\Tests\DataObjects;

use Dealerdirect\Agreements\DataObjects\Font;
use Dealerdirect\Agreements\Exceptions\FileNotFoundException;
use Dealerdirect\Agreements\Tests\TestCase;
use Dompdf\Dompdf;

/**
 * @covers \Dealerdirect\Agreements\DataObjects\Font
 */
final class FontTest extends TestCase
{
    /**
     * @uses \Dealerdirect\Agreements\Exceptions\FileNotFoundException
     */
    public function test_construct_with_invalid_path_should_throw_exception(): void
    {
        $this->expectException(FileNotFoundException::class);

        new Font('font-family', 'bold', 'invalid-path');
    }

    public function test_method_register(): void
    {
        $fontMetrics = (new Dompdf())->getFontMetrics();

        $randomFontDestination = $fontMetrics->getOptions()->getFontDir() . '/Random font.ttf';
        if (file_exists($randomFontDestination)) {
            @unlink($randomFontDestination);
        }

        $font = new Font('Random font', 'normal', $this->getResourcesPath() . '/fonts/Random font.ttf');
        $font->register($fontMetrics);

        $this->assertFileExists($fontMetrics->getOptions()->getFontDir() . '/Random font.ttf');

        $installedFont = $fontMetrics->getFont('Random font');
        $this->assertNotNull($installedFont);
        $this->assertFileExists("$installedFont.ttf");
        $this->assertFileExists("$installedFont.ufm");

        unlink("$installedFont.ttf");
        unlink("$installedFont.ufm");

        $installedFonts = json_decode(file_get_contents($fontMetrics->getUserFontsFilePath()), true);
        $this->assertArrayHasKey('random font', $installedFonts);
        unset($installedFonts['random font']);
        file_put_contents($fontMetrics->getUserFontsFilePath(), json_encode($installedFonts, JSON_PRETTY_PRINT));
    }
}
