<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;

use App\Classes\Protocol\EMSI;
use App\Classes\Sock\SocketClient;
use App\Models\{Address,Setup};

class EMSISend extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'emsi:send {ftn : FTN to Send to}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'EMSI send';

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 * @throws \App\Classes\Sock\SocketException
	 */
	public function handle()
	{
		Log::info('Call EMSI send');

		$no = Address::findFTN($this->argument('ftn'));
		if (! $no)
			throw new ModelNotFoundException('Unknown node: '.$this->argument('ftn'));

		if ($no->system->mailer_type != Setup::O_EMSI)
			throw new \Exception(sprintf('Node [%s] doesnt support EMSI',$this->argument('ftn')));

		if ((! $no->system->mailer_address) || (! $no->system->mailer_port))
			throw new \Exception(sprintf('Unable to poll [%s] missing mailer details',$this->argument('ftn')));

		$client = SocketClient::create($no->system->mailer_address,$no->system->mailer_port,38400);

		$o = new EMSI(Setup::findOrFail(config('app.id')));
		$o->session(EMSI::SESSION_AUTO,$client,$no);

		Log::info(sprintf('Connection ended: %s',$client->address_remote),['m'=>__METHOD__]);
	}
}