<?php

namespace App\Traits;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

use App\Models\{Address,System,Zone};

trait ParseAddresses
{
	/**
	 * Parse the Seenby/path lines and return a collection of addresses
	 *
	 * @param string $type Type of address, ie: seenby/path
	 * @param Collection $addresses
	 * @param Zone $zone
	 * @param Collection $rogue
	 * @return Collection
	 * @throws \Exception
	 */
	private static function parseAddresses(string $type,Collection $addresses,Zone $zone,Collection &$rogue): Collection
	{
		$nodes = collect();

		$net = NULL;
		foreach ($addresses as $line) {
			foreach (explode(' ',$line) as $item) {
				if (($x=strpos($item,'/')) !== FALSE) {
					$net = (int)substr($item,0,$x);
					$node = (int)substr($item,$x+1);

				} else {
					$node = (int)$item;
				}

				// If domain should be flattened, look for node regardless of zone (within the list of zones for the domain)
				$ao = ($zone->domain->flatten)
					? Address::findZone($zone->domain,$net&Address::ADDRESS_FIELD_MAX,$node&Address::ADDRESS_FIELD_MAX,0)
					: Address::findFTN(sprintf('%d:%d/%d@%s',$zone->zone_id,$net&Address::ADDRESS_FIELD_MAX,$node&Address::ADDRESS_FIELD_MAX,$zone->domain->name));

				switch ($type) {
					case 'seenby':
						if (! $ao)
							$rogue->push(sprintf('%d:%d/%d',$zone->domain->flatten ? 0 : $zone->zone_id,$net&Address::ADDRESS_FIELD_MAX,$node&Address::ADDRESS_FIELD_MAX));
						else
							$nodes->push($ao->id);

						break;

					case 'path':
						if (! $ao) {
							$ftn = sprintf('%d:%d/%d@%s',$zone->zone_id,$net&Address::ADDRESS_FIELD_MAX,$node&Address::ADDRESS_FIELD_MAX,$zone->domain->name);

							Log::info(sprintf('%s:- Creating address [%s] for path',self::LOGKEY,$ftn));
							$ao = Address::createFTN($ftn,System::createUnknownSystem());
						}

						$nodes->push($ao->id);

						break;
				}
			}
		}

		return $nodes;
	}
}