<?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\{Binkp,EMSI};
use App\Classes\Sock\SocketClient;
use App\Classes\Sock\SocketException;
use App\Models\{Address,Setup};

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

	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	private Address $ao;

	public function __construct(Address $ao)
	{
		// Some checks
		$this->ao = $ao;
	}

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

		try {
			$client = SocketClient::create($this->ao->system->mailer_address,$this->ao->system->mailer_port);

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

		switch ($this->ao->system->mailer_type) {
			case Setup::O_BINKP:
				$o = new Binkp(Setup::findOrFail(config('app.id')));
				$o->session(Binkp::SESSION_BINKP,$client,$this->ao);

				break;

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

				break;

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

		Log::info(sprintf('%s:Connection ended: %s',self::LOGKEY,$client->address_remote));
	}
}