<?php

namespace App\Tests\Unit\Service\Export\Encoder;

use App\Service\Export\Encoder\PdfEncoder;
use App\Service\Utils\PathUtils;
use Dompdf\Dompdf;
use Dompdf\Options;
use PHPUnit\Framework\TestCase;

class TestablePdfEncoder extends PdfEncoder
{
    public function setDomPdfOptions(Options $options): void
    {
        $this->domPdfOptions = $options;
    }

    public function setDomPdf(Dompdf $dompdf): void
    {
        $this->dompdf = $dompdf;
    }
}

class PdfEncoderTest extends TestCase
{
    /**
     * @see PdfEncoder::support()
     */
    public function testSupport(): void
    {
        $encoder = $this->getMockBuilder(PdfEncoder::class)
            ->disableOriginalConstructor()
            ->setMethodsExcept(['support'])
            ->getMock();

        $this->assertTrue($encoder->support('pdf'));
        $this->assertFalse($encoder->support('txt'));
    }

    /**
     * @see PdfEncoder::encode()
     */
    public function testEncode(): void
    {
        $encoder = $this->getMockBuilder(TestablePdfEncoder::class)
            ->disableOriginalConstructor()
            ->setMethodsExcept(['encode', 'setDomPdfOptions', 'setDomPdf'])
            ->getMock();

        $domPdfOptions = $this->getMockBuilder(Options::class)->disableOriginalConstructor()->getMock();
        $domPdf = $this->getMockBuilder(Dompdf::class)->disableOriginalConstructor()->getMock();
        $encoder->setDomPdfOptions($domPdfOptions);
        $encoder->setDomPdf($domPdf);

        $domPdfOptions->expects(self::once())->method('setIsRemoteEnabled')->with(true);
        $domPdfOptions->expects(self::once())->method('setChroot')->with(PathUtils::getProjectDir().'/public');
        $domPdfOptions->expects(self::once())->method('setDefaultPaperOrientation')->with('portrait');
        $domPdfOptions->expects(self::once())->method('setDefaultPaperSize')->with('A4');
        $domPdfOptions->expects(self::once())->method('set')->with(['additionalOption' => 2]);

        $domPdf->expects(self::once())->method('setOptions')->with($domPdfOptions);
        $domPdf->expects(self::once())->method('loadHtml')->with('<div>content</div>');
        $domPdf->expects(self::once())->method('render');
        $domPdf->expects(self::once())->method('output')->willReturn('%%encoded%%');

        $this->assertEquals(
            '%%encoded%%',
            $encoder->encode('<div>content</div>', ['additionalOption' => 2])
        );
    }
}
