<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models\telegram\middlewares;

// Files of the project
use kodorvan\neurobot\models\core,
	kodorvan\neurobot\models\account as model,
	kodorvan\neurobot\models\localization,
	kodorvan\neurobot\models\authorizations;

// The library for languages support
use mirzaev\languages\language;

// The library for escaping all markdown symbols
use function mirzaev\unmarkdown;

// Framework for Telegram
use SergiX44\Nutgram\Nutgram as telegram,
	SergiX44\Nutgram\Telegram\Properties\ParseMode as mode;

// Built-in libraries
use Error as error;

/**
 * Telegram middleware: welcome
 *
 * @package kodorvan\neurobot\models\telegram\middlewares
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class welcome extends core
{
	/**
	 * Welcome
	 *
	 * Send a welcome message to the chat if it has not already been sent
	 * Information about whether an account has already received a welcome 
	 * message is stored in the `account::$file` database.	 *
	 *
	 * @param telegram $robot
	 * @param $next
	 *
	 * @return void
	 */
	public function __invoke(telegram $robot, $next): void
	{
		// Is the process stopped?
		if ($robot->get('stop')) return;

		// Initializing the account
		$account = $robot->get('account');

		if ($account->welcome === 1) {
			// Has already been sent a welcome message

			// Continuation of the process
			$next($robot);
		} else {
			// Has not already been sent a welcome message

			// Initializing localization
			$localization = $robot->get('localization') ?? new localization(LANGUAGE_DEFAULT);

			if ($localization) {
				// Initialized localization

				// Writing the status of sending the welcome message
				$account->welcome = 1;

				// Serializing the account
				$account->serialize();

				// Writing the account record into the database;
				$account->update();

				// Deserializing the account
				$account->deserialize();

				// Writing the account into the context variable
				$robot->set('account', $account);

				// Sending the message
				$robot->sendMessage(
					text: unmarkdown(text: sprintf(
						$localization->welcome,
						$account->name_first ? ", $account->name_first" : ''
					)),
					parse_mode: mode::MARKDOWN
				);

				// Continuation of the process
				$next($robot);
			}
		}
	}
}
