<?php

namespace Doom\Texture;

use RuntimeException;
use Shufflingpixels\IO\BinaryReader;

final class PNamesParser
{
    /**
     * @return string[]
     */
    public static function parseBytes(string $data): array
    {
        return self::parse(BinaryReader::string($data));
    }

    /**
     * @return string[]
     */
    public static function parse(BinaryReader $reader): array
    {
        if ($reader->length() < 4) {
            throw new RuntimeException('PNAMES lump is too small.');
        }

        $count = $reader->readUInt32LE();
        $requiredBytes = 4 + ($count * 8);
        if ($requiredBytes > $reader->length()) {
            throw new RuntimeException('PNAMES lump is truncated.');
        }

        $names = [];
        for ($i = 0; $i < $count; $i++) {
            $names[] = strtoupper(rtrim($reader->read(8), "\0 "));
        }

        return $names;
    }
}
