<?php

namespace App\Media\QuickTime\Atoms\moov\meta;

// Item LiST container atom

use App\Media\QuickTime\Atoms\SubAtom;

class ilst extends SubAtom
{
	public function __construct(int $offset,int $size,string $filename,?string $data)
	{
		parent::__construct($offset,$size,$filename);

		$ptr = 0;
		while ($ptr < strlen($data)) {
			$key_size = unpack('Nsize',substr($data,$ptr,4));
			// Sometimes atoms are terminated with a 0
			if ($key_size['size'] === 0) {
				$ptr += 4;
				continue;
			}

			$a = unpack(sprintf('a4name/a%ddata',$key_size['size']-8),substr($data,$ptr+4,4+$key_size['size']-8));
			$ptr += $key_size['size'];

			// If we didnt get the right amount of data, something is wrong.
			if (strlen($a['data']) < $key_size['size']-8)
				break;

			$b = unpack(sprintf('Nsize/a4name/a%ddata',strlen($a['data'])-8),$a['data']);

			if ($b['name'] !== 'data')
				throw new \Exception('Parsing of ILST got data that wasnt expected');
			$c = unpack(sprintf('a4language/a4unknown/a%ddata',strlen($b['data'])-8),$b['data']);

			// heirachy, name, size, offset
			$this->cache = $this->cache->push($c['data']);
		}
	}
}