<?php

namespace App\Media\QuickTime\Atoms\moov;

use Illuminate\Support\Arr;

use App\Media\QuickTime\Atoms\moov\meta\{ilst,keys};
use App\Media\QuickTime\Atoms\{SubAtom,Unknown};

class meta extends SubAtom
{
	private const subatom_classes = 'App\\Media\\QuickTime\\Atoms\\moov\\meta\\';

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

		$this->atoms = $this->get_atoms(self::subatom_classes,Unknown::class,$offset,$size,$data);

		$keys = $this->find_atoms(keys::class,1);
		$values = $this->find_atoms(ilst::class,1);

		$this->cache = $keys->cache->combine($values->cache);
	}

	public function __get(string $key): mixed
	{
		switch ($key) {
			case 'gps':
				$m = [];
				$gps = Arr::get($this->cache,'mdta.com.apple.quicktime.location.ISO6709');
				preg_match('/^([+-][0-9]{2,6}(?:\.[0-9]+)?)([+-][0-9]{3,7}(?:\.[0-9]+)?)([+-][0-9]+(?:\.[0-9]+)?)?/',$gps,$m);

				return ['lat'=>(float)$m[1],'lon'=>(float)$m[2],'alt'=>(float)$m[3]];

			case 'gps_altitude':
				return Arr::get($this->gps,'alt');
			case 'gps_lat':
				return Arr::get($this->gps,'lat');
			case 'gps_lon':
				return Arr::get($this->gps,'lon');

			case 'make':
			case 'model':
			case 'software':
				return Arr::get($this->cache,'mdta.com.apple.quicktime.'.$key);

			default:
				return parent::__get($key);
		}
	}
}