<?php

namespace App\Classes;

use App\Models\{Address,Zone};

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

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

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

			case 'fftn_o':
				return Address::findFTN($this->fftn);
			case 'tftn_o':
				return Address::findFTN($this->tftn);

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

	/**
	 * Determine if a line is a kludge line.
	 *
	 * @param string $kludge
	 * @param string $string
	 * @return string
	 */
	protected function kludge(string $kludge,string $string)
	{
		return (preg_match("/^{$kludge}/",$string))
			? chop(preg_replace("/^{$kludge}/",'',$string),"\r")
			: FALSE;
	}

	/**
	 * This function creates our unpack header
	 *
	 * @param array $pack
	 * @return string
	 */
	protected static function unpackheader(array $pack): string
	{
		return join('/',
			collect($pack)
				->sortBy(function($k,$v) {return $k[0];})
				->transform(function($k,$v) {return $k[1].$v;})
				->values()
				->toArray()
		);
	}
}