<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

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

class AddressPoll implements ShouldQueue
{
	private const LOGKEY = 'JAP';

	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	private Address $ao;
	private ?Mailer $mo;

	public function __construct(Address $ao,Mailer $mo=NULL)
	{
		$this->ao = $ao;
		$this->mo = $mo;
	}

	/**
	 * When calling MessageProcess - we assume that the packet is from a valid source
	 */
	public function handle()
	{
		if (! $this->ao->system->mailer_preferred->count() || ($this->mo && (! $this->ao->system->mailer_preferred->find($this->mo))))
			throw new \Exception(sprintf('Unable to poll [%s] missing mailer details',$this->ao->ftn));


		foreach ($this->ao->system->mailer_preferred as $o) {
			// If we chose a protocol, skip to find the mailer details for it
			if ($this->mo && ($o->id !== $this->mo->id))
				continue;

			Log::info(sprintf('%s:- Starting a [%s] session to [%s:%d]',self::LOGKEY,$o->name,$this->ao->system->address,$o->pivot->port));

			try {
				$client = SocketClient::create($this->ao->system->address,$o->pivot->port);

			} catch (SocketException $e) {
				Log::error(sprintf('%s:! Unable to connect to [%s]: %s',self::LOGKEY,$this->ao->ftn,$e->getMessage()));
				abort(500);
			}

			switch ($o->name) {
				case 'BINKP':
					$s = new Binkp(Setup::findOrFail(config('app.id')));
					$session = Binkp::SESSION_BINKP;

					break;

				case 'EMSI':
					$s = new EMSI(Setup::findOrFail(config('app.id')));
					$session = EMSI::SESSION_AUTO;

					break;

				default:
					throw new \Exception(sprintf('Node [%s] has a mailer type that is unhandled',$this->ao->ftn));
			}

			if (($s->session($session,$client,$this->ao) & Protocol::S_MASK) === Protocol::S_OK) {
				Log::info(sprintf('%s:= Connection ended successfully with [%s]',self::LOGKEY,$client->address_remote));
				break;

			} else {
				Log::alert(sprintf('%s:! Connection failed to [%s]',self::LOGKEY,$client->address_remote));
			}
		}
	}
}