<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models\telegram\middlewares;

// Files of the project
use kodorvan\neurobot\models\core,
	kodorvan\neurobot\models\chat,
	kodorvan\neurobot\models\account as model,
	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: chat
 *
 * @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 network extends core
{
	/**
	 * Network
	 *
	 * Check the account for access to the neural network
	 *
	 * @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');

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

		// Initializing the account chat
		$chat = $account?->chat();

		if ($chat instanceof chat) {
			// Initialized the account chat

			if ($authorizations?->{$chat->network->name} ?? false) {
				// Authorized the account to the neural network

				// Continuation of the process
				$next($robot);
			} else {
				// Not authorized the account to the neural network

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

				// Sending the message
				$robot->sendMessage(
					text: "⛔ *$localization->not_authorized_neural_network:* " . unmarkdown(text: $chat->network->value ?? 'error'),
					parse_mode: mode::MARKDOWN
				);

				// Ending the conversation process
				$robot->endConversation();

				// Ending the process
				$robot->set('stop', true);
			}
		} else {
			// Failed to initialize the account chat

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

			// Sending the message
			$robot->sendMessage(
				text: "⛔ *$localization->chat_initialization_fail*",
				parse_mode: mode::MARKDOWN
			);

			// Ending the conversation process
			$robot->endConversation();

			// Ending the process
			$robot->set('stop', true);
		}
	}
}
