<?php

namespace App\Traits;

use Illuminate\Support\Arr;

use App\Models\{Node,Zone};

trait GetNode
{
	/**
	 * Get an FTN record
	 * If the record doesnt exist, we'll create it
	 */
	protected function get_node(array $address,$create=TRUE)
	{
		if (! $z=Arr::get($address,'z'))
			throw new \Exception('Zone cannot be zero');

		$zo = Zone::firstOrCreate(['id'=>$z]);

		$no = Node::firstOrNew([
			'zone_id'=>$zo->id,
			'host_id'=>Arr::get($address,'n'),
			'node_id'=>Arr::get($address,'f'),
			'point_id'=>Arr::get($address,'p',0)
		]);

		if (! $no->exists AND $create)
		{
			$no->active = FALSE;
			$no->system = 'AUTO DISCOVERED';
			$no->sysop = 'UNKNOWN';
			$no->location = '';
			$no->baud = 0;

			$no->save();
		}

		return ($no->exists) ? $no : NULL;
	}
}