<?php

namespace App\Classes;

use App\Models\{Address,Zone};

abstract class FTN
{
	protected ?Zone $zone;				// Zone the packet is from

	public function __get(string $key)
	{
		switch ($key) {
			case 'fftn_t':
				return sprintf('%d:%d/%d.%d',
					$this->fz,
					$this->fn,
					$this->ff,
					$this->fp,
				).((isset($this->zone) && $this->zone) ? sprintf('@%s',$this->zone->domain->name) : '');

			case 'tftn_t':
				return sprintf('%d:%d/%d.%d',
					$this->tz,
					$this->tn,
					$this->tf,
					$this->tp,
				).((isset($this->zone) && $this->zone) ? sprintf('@%s',$this->zone->domain->name) : '');

			case 'fftn':
				return Address::findFTN($this->fftn_t);
			case 'tftn':
				return Address::findFTN($this->tftn_t);

			default:
				throw new \Exception('Unknown key: '.$key);
		}
	}

	/**
	 * This function creates our unpack header
	 *
	 * @param array $pack
	 * @return string
	 * @throws \Exception
	 */
	protected static function unpackheader(array $pack): string
	{
		// Check that our header is correct
		if (app()->environment('local')) {
			$c = 0;
			foreach (collect($pack) as $item) {
				if ($c !== $item[0])
					throw new \Exception('Invalid header');

				$c += $item[2];
			}
		}

		return collect($pack)
			->sortBy(function($k,$v) {return $k[0];})
			->transform(function($k,$v) {return $k[1].$v;})
			->values()
			->join('/');
	}
}