<?php

declare(strict_types=1);

namespace Intervention\Gif\Encoders;

use Intervention\Gif\Blocks\PlainTextExtension;

class PlainTextExtensionEncoder extends AbstractEncoder
{
    /**
     * Create new instance.
     */
    public function __construct(PlainTextExtension $entity)
    {
        $this->entity = $entity;
    }

    /**
     * Encode current entity.
     */
    public function encode(): string
    {
        if (!$this->entity->hasText()) {
            return '';
        }

        return implode('', [
            PlainTextExtension::MARKER,
            PlainTextExtension::LABEL,
            $this->encodeHead(),
            $this->encodeTexts(),
            PlainTextExtension::TERMINATOR,
        ]);
    }

    /**
     * Encode head block.
     */
    private function encodeHead(): string
    {
        return "\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
    }

    /**
     * Encode text chunks.
     */
    private function encodeTexts(): string
    {
        return implode('', array_map(
            fn(string $text): string => pack('C', strlen($text)) . $text,
            $this->entity->text(),
        ));
    }
}
