<?php

namespace App\Console\Commands;

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

use App\Classes\Protocol\Binkp;
use App\Classes\Sock\Exception\SocketException;
use App\Classes\Sock\SocketServer;
use App\Models\Setup;

class CommBinkpReceive extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'comm:binkp:receive';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'BINKP receive';

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 * @throws SocketException
	 */
	public function handle()
	{
		Log::info('Listening for BINKP connections...');
		$o = Setup::findOrFail(config('app.id'));

		$server = new SocketServer($o->binkp_port,$o->binkp_bind);
		$server->handler = [new Binkp,'onConnect'];

		try {
			$server->listen();

		} catch (SocketException $e) {
			if ($e->getMessage() === 'Can\'t accept connections: "Success"')
				Log::debug('Server Terminated');
			else
				Log::emergency('Uncaught Message: '.$e->getMessage());
		}
	}
}