<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

use App\Classes\FTN\{Message,Packet};
use App\Exceptions\InvalidFTNException;
use App\Traits\ScopeActive;

class Address extends Model
{
	use ScopeActive,SoftDeletes;

	private const LOGKEY = 'MA-';

	protected $with = ['zone'];

	// http://ftsc.org/docs/frl-1028.002
	public const ftn_regex = '(\d+):(\d+)/(\d+)(?:\.(\d+))?(?:@([a-zA-Z0-9\-_~]{0,8}))?';

	public const NODE_ZC		= 1<<0;		// Zone
	public const NODE_RC		= 1<<1;		// Region
	public const NODE_NC		= 1<<2;		// Host
	public const NODE_HC		= 1<<3;		// Hub
	public const NODE_ACTIVE	= 1<<4;		// Node
	public const NODE_PVT		= 1<<5;		// Pvt
	public const NODE_HOLD		= 1<<6;		// Hold
	public const NODE_DOWN		= 1<<7;		// Down
	public const NODE_POINT		= 1<<8;		// Point
	public const NODE_UNKNOWN	= 1<<15;	// Unknown
	public const NODE_ALL		= 0xFFF;	// Mask to catch all nodes

	// http://ftsc.org/docs/frl-1002.001
	public const ADDRESS_FIELD_MAX = 0x7fff;	// Maximum value for a field in the address

	public static function boot()
	{
		parent::boot();

		// For indexes when deleting, we need to change active to FALSE
		static::softDeleted(function($model) {
			Log::debug(sprintf('%s:Deleting [%d], updating active to FALSE',self::LOGKEY,$model->id));

			$model->active = FALSE;
			$model->save();
		});
	}

	protected $visible = ['zone_id','region_id','host_id','node_id','point_id','security'];

	/* SCOPES */

	public function scopeActiveFTN($query)
	{
		return $query->select($this->getTable().'.*')
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->join('domains',['domains.id'=>'zones.domain_id'])
			->where('addresses.active',TRUE)
			->where('zones.active',TRUE)
			->where('domains.active',TRUE)
			->orderBy('domains.name')
			->FTNorder();
	}

	public function scopeFTNOrder($query)
	{
		return $query
			->orderBy('region_id')
			->orderBy('host_id')
			->orderBy('node_id')
			->orderBy('point_id');
	}

	public function scopeFTN2DOrder($query)
	{
		return $query
			->orderBy('host_id')
			->orderBy('node_id')
			->orderBy('point_id');
	}

	public function scopeTrashed($query)
	{
		return $query->select($this->getTable().'.*')
			->withTrashed()
			->FTNorder();
	}

	/**
	 * Return a list of addresses and the amount of uncollected echomail
	 *
	 * @param $query
	 * @return mixed
	 */
	public function scopeUncollectedEchomail($query)
	{
		return $query
			->join('echomail_seenby',['echomail_seenby.address_id'=>'addresses.id'])
			->join('echomails',['echomails.id'=>'echomail_seenby.echomail_id'])
			->whereNotNull('export_at')
			->whereNull('sent_at')
			->whereNull('echomails.deleted_at')
			->groupBy('addresses.id');
	}

	public function scopeUncollectedEchomailTotal($query)
	{
		return $query
			->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('count(*) as uncollected_echomail'),DB::raw('0 as uncollected_netmail'),DB::raw('0 as uncollected_files')])
			->UncollectedEchomail();
	}

	/**
	 * Return a list of addresses and the amount of uncollected files
	 *
	 * @param $query
	 * @return mixed
	 */
	public function scopeUncollectedFiles($query)
	{
		return $query
			->join('file_seenby',['file_seenby.address_id'=>'addresses.id'])
			->join('files',['files.id'=>'file_seenby.file_id'])
			->whereNotNull('export_at')
			->whereNull('sent_at')
			->whereNull('files.deleted_at')
			->groupBy('addresses.id');
	}

	public function scopeUncollectedFilesTotal($query)
	{
		return $query
			->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('0 as uncollected_echomail'),DB::raw('0 as uncollected_netmail'),DB::raw('count(*) as uncollected_files')])
			->UncollectedFiles();
	}

	public function scopeUncollectedNetmail($query)
	{
		return $query
			->join('netmails',['netmails.tftn_id'=>'addresses.id'])
			->where(function($query) {
				return $query->whereRaw(sprintf('(flags & %d) > 0',Message::FLAG_INTRANSIT))
					->orWhereRaw(sprintf('(flags & %d) > 0',Message::FLAG_LOCAL));
			})
			->whereRaw(sprintf('(flags & %d) = 0',Message::FLAG_SENT))
			->whereNull('sent_pkt')
			->whereNull('sent_at')
			->whereNull('netmails.deleted_at')
			->groupBy('addresses.id');
	}

	/**
	 * Return a list of addresses and the amount of uncollected netmail
	 *
	 * @param $query
	 * @return mixed
	 */
	public function scopeUncollectedNetmailTotal($query)
	{
		return $query
			->select(['addresses.id','zone_id','host_id','node_id','point_id','system_id',DB::raw('0 as uncollected_echomail'),DB::raw('count(*) as uncollected_netmail'),DB::raw('0 as uncollected_files')])
			->UncollectedNetmail();
	}

	/* RELATIONS */

	public function dynamics()
	{
		return $this->hasMany(Dynamic::class);
	}

	/**
	 * Echoareas this address is subscribed to
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function echoareas()
	{
		return $this->belongsToMany(Echoarea::class)
			->withPivot(['subscribed']);
	}

	/**
	 * Echomails that this address has seen
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function echomails()
	{
		return $this->belongsToMany(Echomail::class,'echomail_seenby')
			->withPivot(['export_at','sent_at','sent_pkt']);
	}

	public function echomail_from()
	{
		return $this->hasMany(Echomail::class,'fftn_id','id');
	}

	/**
	 * Files that this address has seen
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function files()
	{
		return $this->belongsToMany(File::class,'file_seenby')
			->withPivot(['sent_at','export_at']);
	}

	/**
	 * Fileareas this address is subscribed to
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function fileareas()
	{
		return $this->belongsToMany(Filearea::class)
			->withPivot(['subscribed']);
	}

	public function system()
	{
		return $this->belongsTo(System::class);
	}

	public function zone()
	{
		return $this->belongsTo(Zone::class);
	}

	/* ATTRIBUTES */

	/**
	 * Return if this address is active
	 *
	 * @param bool $value
	 * @return bool
	 */
	public function getActiveAttribute(bool $value): bool
	{
		return $value && $this->getActiveDomainAttribute();
	}

	public function getActiveDomainAttribute(): bool
	{
		return $this->zone->active && $this->zone->domain->active;
	}

	/**
	 * Render the node name in full 5D
	 *
	 * @return string
	 */
	public function getFTNAttribute(): string
	{
		return sprintf('%s@%s',$this->getFTN4DAttribute(),$this->zone->domain->name);
	}

	public function getFTN2DAttribute(): string
	{
		return sprintf('%d/%d',$this->host_id ?: $this->region_id,$this->node_id);
	}

	public function getFTN3DAttribute(): string
	{
		return sprintf('%d:%s',$this->zone->zone_id,$this->getFTN2DAttribute());
	}

	public function getFTN4DAttribute(): string
	{
		return sprintf('%s.%d',$this->getFTN3DAttribute(),$this->point_id);
	}

	public function getRoleNameAttribute(): string
	{
		switch ($this->role) {
			case self::NODE_ZC:
				return 'ZC';
			case self::NODE_RC:
				return 'RC';
			case self::NODE_NC:
				return 'NC';
			case self::NODE_HC:
				return 'HUB';
			case self::NODE_ACTIVE:
				return 'NODE';
			case self::NODE_POINT:
				return 'POINT';
			case self::NODE_PVT:
				return 'PRIVATE';
			default:
				return '?';
		}
	}

	/* METHODS */

	/**
	 * Find children dependent on this record
	 */
	public function children(): Collection
	{
		// We have no session data for this address, by definition it has no children
		if (! $this->session('sespass') && (! our_address()->pluck('id')->contains($this->id)))
			return new Collection;

		// If this system is not marked to default route for this address
		if (! $this->session('default')) {
			switch ($this->role) {
				case self::NODE_ZC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id);

					break;

				case self::NODE_RC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id);

					break;

				case self::NODE_NC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id)
						->where('host_id',$this->host_id);

					break;

				case self::NODE_HC:
					// Identify our children.
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id)
						->where('hub_id',$this->id);

					break;

				case self::NODE_ACTIVE:
				case self::NODE_PVT:
				case self::NODE_HOLD:
				case self::NODE_DOWN:
				case self::NODE_UNKNOWN:
					// Identify our children.
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id)
						->where('host_id',$this->host_id)
						->where('node_id',$this->node_id)
						->where('point_id','<>',0);
					break;

				case self::NODE_POINT:
					// Points dont have children, but must return a relationship instance
					return new Collection;

				default:
					throw new \Exception('Unknown role: '.serialize($this->role));
			}

			// We route everything for this domain
		} else {
			$children = self::select('addresses.*')
				->join('zones',['zones.id'=>'addresses.zone_id'])
				->where('domain_id',$this->zone->domain_id);
		}

		// I cant have myself as a child, and have a high role than me
		$children = $children->where('addresses.id','<>',$this->id)
			->where('role','>',$this->role)
			->FTNorder()
			->active()
			->get();

		// If there are no children
		if (! $children->count())
			return new Collection;

		// Exclude links and their children.
		$exclude = collect();
		foreach (our_nodes($this->zone->domain)->merge(our_address($this->zone->domain)) as $o) {
			// If this address is in our list, remove it and it's children
			if ($children->contains($o)) {
				$exclude = $exclude->merge($o->children());
				$exclude->push($o);
			}
		}

		return $children->filter(function($item) use ($exclude) { return ! $exclude->pluck('id')->contains($item->id);});
	}

	/**
	 * Create an FTN address associated with a system
	 *
	 * @param string $address
	 * @param System $so
	 * @return Address|null
	 * @throws \Exception
	 */
	public static function createFTN(string $address,System $so): ?self
	{
		$ftn = self::parseFTN($address);

		if (! $ftn['d']) {
			// See if we have a default domain for this domain
			if ($ftn['z']) {
				$zo = Zone::where('zone_id',$ftn['z'])->where('default',TRUE)->single();

				if ($zo)
					$ftn['d'] = $zo->domain->name;

				else {
					Log::alert(sprintf('%s:! Refusing to create address [%s] no domain available',self::LOGKEY,$address));

					return NULL;
				}
			}
		}

		Log::debug(sprintf('%s:- Creating AKA [%s] for [%s]',self::LOGKEY,$address,$so->name));

		// Check Domain exists
		Domain::unguard();
		$do = Domain::singleOrNew(['name'=>$ftn['d']]);
		Domain::reguard();

		if (! $do->exists) {
			$do->public = TRUE;
			$do->active = TRUE;
			$do->notes = 'Auto created';

			$do->save();
		}

		// If the zone is zero, see if this is a flatten domain, and if so, find an NC
		if (($ftn['z'] === 0) && $do->flatten) {
			$nc = self::findZone($do,$ftn['n'],0,0);

			if ($nc) {
				Log::info(sprintf('%s:- Setting zone to [%d]',self::LOGKEY,$nc->zone->zone_id));
				$ftn['z'] = $nc->zone->zone_id;
			}
		}

		// Create zone
		Zone::unguard();
		$zo = Zone::singleOrNew(['domain_id'=>$do->id,'zone_id'=>$ftn['z']]);
		Zone::reguard();

		if (! $zo->exists) {
			$zo->active = TRUE;
			$zo->notes = 'Auto created';
			$zo->system_id = System::createUnknownSystem()->id;

			$do->zones()->save($zo);
		}

		if (! $zo->active || ! $do->active) {
			Log::alert(sprintf('%s:! Refusing to create address [%s] in disabled zone or domain',self::LOGKEY,$address));

			return NULL;
		}

		// Create Address, assigned to $so
		$o = new self;
		$o->active = TRUE;
		$o->zone_id = $zo->id;
		$o->region_id = 0;
		$o->host_id = $ftn['n'];
		$o->node_id = $ftn['f'];
		$o->point_id = $ftn['p'];
		$o->role = $ftn['p'] ? self::NODE_POINT : self::NODE_UNKNOWN;

		try {
			$so->addresses()->save($o);

		} catch (QueryException $e) {
			Log::error(sprintf('%s:! ERROR creating address [%s] (%s)',self::LOGKEY,$o->ftn,get_class($e)));
			return NULL;
		}

		return $o;
	}

	/**
	 * Find a record in the DB for a node string, eg: 10:1/1.0
	 *
	 * @param string $address
	 * @param bool $trashed
	 * @return Address|null
	 * @throws \Exception
	 */
	public static function findFTN(string $address,bool $trashed=FALSE): ?self
	{
		$ftn = self::parseFTN($address);
		$o = NULL;

		$query = (new self)
			->select('addresses.*')
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->join('domains',['domains.id'=>'zones.domain_id'])
			->when($trashed,function($query) {
				$query->trashed();
			},function($query) {
				$query->active();
			})
			->where('zones.zone_id',$ftn['z'])
			->where('node_id',$ftn['f'])
			->where('point_id',$ftn['p'])
			->when($ftn['d'],function($query,$domain) {
				$query->where('domains.name',$domain);
			},function($query) {
				$query->where('zones.default',TRUE);
			});

		$q = $query->clone();

		// Are we looking for a region address
		if (($ftn['f'] === 0) && ($ftn['p'] === 0))
			$o = $query
				->where('region_id',$ftn['n'])
				->where('host_id',$ftn['n'])
				->single();

		// Look for a normal address
		if (! $o)
			$o = $q
				->where(function($q) use ($ftn) {
					return $q
						->where(function($q) use ($ftn) {
							return $q
								->where('region_id',$ftn['n'])
								->where('host_id',$ftn['n']);
							})
						->orWhere('host_id',$ftn['n']);
				})
				->single();

		// Check and see if we are a flattened domain, our address might be available with a different zone.
		if (! $o && ($ftn['p'] === 0)) {
			if ($ftn['d'])
				$do = Domain::where(['name'=>$ftn['d']])->single();
			else {
				$zo = Zone::where('zone_id',$ftn['z'])->where('default',TRUE)->single();
				$do = $zo?->domain;
			}

			if ($do && $do->flatten && (($ftn['z'] === 0) || $do->zones->pluck('zone_id')->contains($ftn['z'])))
				$o = self::findZone($do,$ftn['n'],$ftn['f'],$ftn['p'],$trashed);
		}

		return ($o && $o->system->active) ? $o : NULL;
	}

	/**
	 * This is to find an address for a domain (like fidonet), which is technically 2D even though it uses multiple zones.
	 *
	 * This was implemented to identify seenby and path kludges
	 *
	 * @param Domain $do
	 * @param int $host
	 * @param int $node
	 * @param int $point
	 * @param bool $trashed
	 * @return self|null
	 * @throws \Exception
	 */
	public static function findZone(Domain $do,int $host,int $node,int $point,bool $trashed=FALSE): ?self
	{
		if (! $do->flatten)
			throw new \Exception(sprintf('Domain is not set with flatten: %d',$do->id));

		$zones = $do->zones->pluck('zone_id');

		$o = (new self)
			->select('addresses.*')
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->when($trashed,function($query) {
				$query->trashed();
			},function($query) {
				$query->active();
			})
			->whereIN('zones.zone_id',$zones)
			->where(function($q) use ($host) {
				return $q
					->where(function($q) use ($host) {
						return $q->where('region_id',$host)
							->where('host_id',$host);
					})
					->orWhere('host_id',$host);
			})
			->where('node_id',$node)
			->where('point_id',$point)
			->where('zones.domain_id',$do->id)
			->single();

		return $o;
	}

	/**
	 * Create an activation code for this address
	 *
	 * @param User $uo
	 * @return string
	 */
	public function set_activation(User $uo): string
	{
		return sprintf('%x:%s',
			$this->id,
			substr(md5(sprintf('%d:%x',$uo->id,timew($this->updated_at))),0,10)
		);
	}

	/**
	 * Check the user's activation code for this address is correct
	 *
	 * @param User $uo
	 * @param string $code
	 * @return bool
	 */
	public function check_activation(User $uo,string $code): bool
	{
		try {
			Log::info(sprintf('%s:Checking Activation code [%s] is valid for user [%d]',self::LOGKEY,$code,$uo->id));

			return ($code === $this->set_activation($uo));

		} catch (\Exception $e) {
			Log::error(sprintf('%s:! Activation code [%s] invalid for user [%d]',self::LOGKEY,$code,$uo->id));

			return FALSE;
		}
	}

	/**
	 * Files waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function dynamicWaiting(): Collection
	{
		return $this->dynamics()
			->where('next_at','<=',Carbon::now())
			->where('active',TRUE)
			->get();
	}

	/**
	 * Echomail waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function echomailWaiting(int $max=NULL): Collection
	{
		$echomails = $this
			->UncollectedEchomail()
			->select('echomails.id')
			->where('addresses.id',$this->id)
			->when($max,function($query) use ($max) { return $query->limit($max); })
			->groupBy(['echomails.id'])
			->get();

		return Echomail::whereIn('id',$echomails->pluck('id'))->get();
	}

	/**
	 * Files waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function filesWaiting(): Collection
	{
		return $this->files()
			->whereNull('sent_at')
			->whereNotNull('export_at')
			->get();
	}

	/**
	 * Get echomail for this node
	 *
	 * @param bool $update
	 * @param Collection|null $echomail
	 * @return Packet|null
	 * @todo If we export to uplink hubs without our address in the seenby, they should send the message back to
	 *       us with their seenby's.
	 */
	public function getEchomail(bool $update=TRUE,Collection $echomail=NULL): ?Packet
	{
		$pkt = NULL;
		if ($echomail)
			return $this->getPacket($echomail);

		$s = Setup::findOrFail(config('app.id'));

		$num = self::UncollectedEchomail()
			->select('echomails.id')
			->where('addresses.id',$this->id)
			->groupBy(['echomails.id'])
			->get();

		if ($num->count()) {
			// Limit to max messages
			Log::info(sprintf('%s:= Got [%d] echomails for [%s] for sending',self::LOGKEY,$num->count(),$this->ftn));

			if ($num->count() > $s->msgs_pkt)
				Log::notice(sprintf('%s:= Only sending [%d] echomails for [%s]',self::LOGKEY,$s->msgs_pkt,$this->ftn));

			$x = $this->echomailWaiting($s->msgs_pkt);
			$pkt = $this->getPacket($x);

			if ($pkt && $pkt->count() && $update)
				DB::table('echomail_seenby')
					->whereIn('echomail_id',$x->pluck('id'))
					->where('address_id',$this->id)
					->whereNull('sent_at')
					->whereNotNull('export_at')
					->update(['sent_pkt'=>$pkt->name]);
		}

		return $pkt;
	}

	/**
	 * Get files for this node (including it's children)
	 *
	 * @param bool $update
	 * @return Collection
	 * @deprecated use filesWaiting() directly
	 */
	public function getFiles(bool $update=TRUE): Collection
	{
		return $this->filesWaiting();
	}

	/**
	 * Get netmail for this node (including it's children)
	 *
	 * @param bool $update
	 * @return Packet|null
	 * @throws \Exception
	 */
	public function getNetmail(bool $update=FALSE): ?Packet
	{
		$pkt = NULL;

		$s = Setup::findOrFail(config('app.id'));

		if (($x=$this->netmailAlertWaiting())->count()) {
			Log::debug(sprintf('%s:= Packaging [%d] netmail alerts to [%s]',self::LOGKEY,$x->count(),$this->ftn));
			$passpos = strpos($x->last()->subject,':');

			if ($passpos > 8)
				Log::alert(sprintf('%s:! Password would be greater than 8 chars? [%d]',self::LOGKEY,$passpos));

			$pkt = $this->getPacket($x,substr($x->last()->subject,0,$passpos));

			if ($pkt && $pkt->count() && $update)
				DB::table('netmails')
					->whereIn('id',$x->pluck('id'))
					->update(['sent_pkt'=>$pkt->name]);

			return $pkt;
		}

		if (($x=$this->netmailWaiting())
			->count())
		{
			Log::debug(sprintf('%s:= Got [%d] netmails for [%s] for sending',self::LOGKEY,$x->count(),$this->ftn));

			if ($x->count() > $s->msgs_pkt) {
				$x = $x->take($s->msgs_pkt);
				Log::alert(sprintf('%s:= Only sending [%d] netmails for [%s]',self::LOGKEY,$x->count(),$this->ftn));
			}

			$pkt = $this->getPacket($x);

			if ($pkt && $pkt->count() && $update)
				DB::table('netmails')
					->whereIn('id',$x->pluck('id'))
					->update(['sent_pkt'=>$pkt->name]);
		}

		return $pkt;
	}

	/**
	 * Return a packet of mail
	 *
	 * @param Collection $msgs of message models (Echomail/Netmail)
	 * @param string|null $passwd Override password used in packet
	 * @return Packet|null
	 */
	public function getPacket(Collection $msgs,string $passwd=NULL): ?Packet
	{
		$s = Setup::findOrFail(config('app.id'));
		$ao = our_address($this->zone->domain,$this);

		// If we dont match on the address, we cannot pack mail for that system
		if (! $ao) {
			Log::alert(sprintf('%s:! We didnt match an address in zone [%d] for [%s]',self::LOGKEY,$this->zone->zone_id,$this->ftn));
			return NULL;
		}

		// Get packet type
		$type = collect(Packet::PACKET_TYPES)->get($this->system->pkt_type ?: config('fido.packet_default'));
		$o = new $type;
		$o->addressHeader($ao,$this,$passwd);

		// $oo = Netmail/Echomail Model
		$c = 0;
		foreach ($msgs as $oo) {
			// Only bundle up to max messages
			if (++$c > $s->msgs_pkt)
				break;

			$o->addMail($oo->packet($this,$passwd));
		}

		return $o;
	}

	/**
	 * Netmail waiting to be sent to this system
	 *
	 * @return Collection
	 * @throws \Exception
	 */
	public function netmailWaiting(): Collection
	{
		$netmails = $this
			->UncollectedNetmail()
			->select('netmails.id')
			->whereIn('addresses.id',$this->children()->add($this)->pluck('id'))
			->groupBy(['netmails.id'])
			->get();

		return Netmail::whereIn('id',$netmails->pluck('id'))->get();
	}

	/**
	 * Netmail alerts waiting to be sent to this system
	 *
	 * @return Collection
	 * @throws \Exception
	 */
	public function netmailAlertWaiting(): Collection
	{
		$netmails = $this
			->UncollectedNetmail()
			->whereRaw(sprintf('(flags & %d) > 0',Message::FLAG_LOCAL))
			->whereRaw(sprintf('(flags & %d) > 0',Message::FLAG_PKTPASSWD))
			->whereRaw(sprintf('(flags & %d) = 0',Message::FLAG_SENT))
			->select('netmails.id')
			->whereIn('addresses.id',$this->children()->add($this)->pluck('id'))
			->groupBy(['netmails.id'])
			->get();

		return Netmail::whereIn('id',$netmails->pluck('id'))->get();
	}

	/**
	 * Who we send this systems mail to.
	 *
	 * @return Address|null
	 * @throws \Exception
	 */
	public function parent(): ?Address
	{
		// If we have session password, then we are the parent
		if ($this->session('sespass'))
			return $this;

		// If it is our address
		if (our_address()->contains($this))
			return NULL;

		switch ($this->role) {
			// ZCs dont have parents, but we may have a default
			case self::NODE_ZC:
				if (($x=$this->zone->systems->where('pivot.default',TRUE))->count())
					return $x->first()->match($this->zone,255)->first();
				else
					return NULL;

			// RC
			case self::NODE_RC:
				$parent = self::where('zone_id',$this->zone_id)
					->where('region_id',0)
					->where('host_id',0)
					->where('node_id',0)
					->single();

				break;

			// Hosts
			case self::NODE_NC:
				// See if we have an RC
				$parent = self::where('zone_id',$this->zone_id)
					->where('region_id',$this->region_id)
					->where('host_id',$this->region_id)
					->where('node_id',0)
					->single();

				if (! $parent) {
					// See if we have an ZC
					$parent = self::where('zone_id',$this->zone_id)
						->where('region_id',0)
						->where('host_id',0)
						->where('node_id',0)
						->single();
				}

				break;

			// Hubs
			case self::NODE_HC:
				// Normal Nodes
			case self::NODE_ACTIVE:
			case self::NODE_PVT:
			case self::NODE_HOLD:
			case self::NODE_DOWN:
			case self::NODE_UNKNOWN:
				// If we are a child of a hub, then check our hub
				$parent = ($this->hub_id
					? self::where('id',$this->hub_id)
					: self::where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id)
						->where('host_id',$this->host_id)
						->where('role','<',self::NODE_HC))
					->active()
					->single();
				break;

			case self::NODE_POINT:
				$parent = self::where('zone_id',$this->zone_id)
					->where('region_id',$this->region_id)
					->where('host_id',$this->host_id)
					->where('node_id',$this->node_id)
					->where('point_id',0)
					->active()
					->single();
				break;

			default:
				throw new \Exception(sprintf('Unknown role: %s (%d)',serialize($this->role),$this->id));
		}

		return $parent?->parent();
	}

	/**
	 *
	 * Parse a string and split it out as an FTN array
	 *
	 * @param string $ftn
	 * @return array
	 * @throws \Exception
	 */
	public static function parseFTN(string $ftn): array
	{
		if (! preg_match(sprintf('#^%s$#',self::ftn_regex),strtolower($ftn),$matches))
			throw new InvalidFTNException(sprintf('Invalid FTN: [%s] - regex failed',serialize($ftn)));

		// Check our numbers are correct.
		foreach ([1,2,3] as $i)
			if ((! is_numeric($matches[$i])) || ($matches[$i] > self::ADDRESS_FIELD_MAX))
				throw new InvalidFTNException(sprintf('Invalid FTN: [%s] - zone, host, or node address invalid [%d]',$ftn,$matches[$i]));

		if ((! empty($matches[4])) AND ((! is_numeric($matches[$i])) || ($matches[4] > self::ADDRESS_FIELD_MAX)))
			throw new InvalidFTNException(sprintf('Invalid FTN: [%s] - point address invalid [%d]',$ftn,$matches[4]));

		return [
			'z'=>(int)$matches[1],
			'n'=>(int)$matches[2],
			'f'=>(int)$matches[3],
			'p'=>empty($matches[4]) ? 0 : (int)$matches[4],
			'd'=>$matches[5] ?? NULL
		];
	}

	/**
	 * Retrieve the address session details/passwords
	 *
	 * @param string $type
	 * @return string|null
	 */
	public function session(string $type): ?string
	{
		return ($this->exists && ($x=$this->system->sessions->where('id',$this->zone_id)->first())) ? ($x->pivot->{$type} ?: '') : NULL;
	}
}