<?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
	 * @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('/');
	}
}