<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

use App\Classes\File;
use App\Classes\FTN\Packet;
use App\Jobs\PacketProcess as Job;
use App\Models\Address;

class PacketProcess extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'packet:process'
		.' {file : Packet to process}'
		.' {--N|nobot : Dont process bots}'
		.' {ftn? : System the packet is from}'
		.' {--Q|dontqueue : Dont queue the message}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Process Packet';

	/**
	 * Execute the console command.
	 *
	 * @return void
	 * @throws \App\Exceptions\InvalidPacketException
	 */
	public function handle()
	{
		$fs = Storage::disk(config('fido.local_disk'));
		$rel_name = sprintf('%s/%s',config('fido.dir'),$this->argument('file'));

		$f = new File($fs->path($rel_name));

		$m = [];
		if ($this->argument('ftn')) {
			$a = Address::findFTN($this->argument('ftn'));

		} elseif (preg_match(sprintf('/^%s\.(.{3})$/',Packet::regex),$this->argument('file'),$m)) {
			$a = Address::findOrFail(hexdec($m[1]));

		} else {
			$this->error('Unable to determine sender FTN address');
			exit(1);
		}

		$x = Job::dispatchSync($rel_name,$a->zone->domain,$this->option('dontqueue'));

		dd(['job completed'=>$x]);
	}
}