<?php

namespace App\Classes\FTN\Process\Netmail;

use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Log;

use App\Classes\FTN\{Message,Process};
use App\Models\{Netmail,Setup};

/**
 * Process messages to Ping
 *
 * @package App\Classes\FTN\Process
 */
final class Ping extends Process
{
	private const LOGKEY = 'RP-';

	private static array $logo = [
		'ÚÄ¿þÚÄ¿ÚÄ¿',
		'³ ³Â³ ³Àij',
		'ÃÄÙÁÁ ÁÄÄÙ'
	];

	public static function handle(Message $msg): bool
	{
		if (strtolower($msg->user_to) !== 'ping')
			return FALSE;

		Log::info(sprintf('%s:- Processing PING message from (%s) [%s]',self::LOGKEY,$msg->user_from,$msg->fftn));
		$ftns = Setup::findOrFail(config('app.id'))->system->match($msg->fftn_o->zone)->first();

		$reply = sprintf("Your ping was received here on %s and it looks like you sent it on %s. If that is correct, then it took %s to get here.\r",
			Carbon::now()->utc()->toDateTimeString(),
			$msg->date->utc()->toDateTimeString(),
			$msg->date->diffForHumans(['parts'=>3,'syntax'=>CarbonInterface::DIFF_ABSOLUTE])
		);

		$reply .= "\r";
		$reply .= "Your message travelled along this path on the way here:\r";
		foreach ($msg->via as $path)
			$reply .= sprintf(" * %s\r",$path);

		$o = new Netmail;
		$o->to = $msg->user_from;
		$o->from = Setup::PRODUCT_NAME;
		$o->subject = 'Ping Reply';
		$o->datetime = Carbon::now();
		$o->tzoffset = $o->datetime->utcOffset();

		$o->reply = $msg->msgid;
		$o->fftn_id = $ftns->id;
		$o->tftn_id = ($x=$msg->fftn_o) ? $x->id : NULL;
		$o->flags = Message::FLAG_LOCAL;
		$o->cost = 0;

		$o->msg = static::format_msg($reply,self::$logo);
		$o->tagline = 'My ping pong opponent was not happy with my serve. He kept returning it.';
		$o->tearline = sprintf('%s (%04X)',Setup::PRODUCT_NAME,Setup::PRODUCT_ID);
		$o->save();

		return TRUE;
	}
}