<?php

namespace App\Classes\FTN\Process;

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 static array $logo = [
		'ÚÄ¿þÚÄ¿ÚÄ¿',
		'³ ³Â³ ³Àij',
		'ÃÄÙÁÁ ÁÄÄÙ'
	];

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

		Log::info(sprintf('Processing PING message from (%s) [%s]',$msg->user_from,$msg->fftn));

		$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",
			$msg->date->toDateTimeString(),
			Carbon::now()->toDateTimeString(),
			$msg->date->diffForHumans(['parts'=>3,'syntax'=>CarbonInterface::DIFF_ABSOLUTE])
		);

		$reply .= "\r";
		$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->fftn_id = ($x=$msg->tftn_o) ? $x->id : NULL;
		$o->tftn_id = ($x=$msg->fftn_o) ? $x->id : NULL;
		$o->msg = static::format_msg($reply,self::$logo);
		$o->reply = $msg->msgid;

		$o->tagline = 'My ping pong opponent was not happy with my serve. He kept returning it.';
		$o->tearline = sprintf('--- %s (%s)',Setup::PRODUCT_NAME,(new Setup)->version);
		$o->save();

		return TRUE;
	}
}