<?php

declare(strict_types=1);

namespace mirzaev\arming_bot\models;

// Files of the project
use mirzaev\arming_bot\models\account,
	mirzaev\arming_bot\models\connect,
	mirzaev\arming_bot\models\enumerations\session as verification,
	mirzaev\arming_bot\models\traits\status,
	mirzaev\arming_bot\models\traits\document as arangodb_document_trait,
	mirzaev\arming_bot\models\interfaces\document as arangodb_document_interface,
	mirzaev\arming_bot\models\enumerations\language;

// Framework for ArangoDB
use mirzaev\arangodb\collection,
	mirzaev\arangodb\document;

// Library для ArangoDB
use ArangoDBClient\Document as _document;

// Built-in libraries
use exception;

/**
 * Model of a session
 *
 * @package mirzaev\arming_bot\models
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class session extends core implements arangodb_document_interface
{
	use status, arangodb_document_trait;

	/**
	 * Name of the collection in ArangoDB
	 */
	final public const string COLLECTION = 'session';

	/**
	 * Type of sessions verification
	 */
	public const verification VERIFICATION = verification::hash_else_address;

	/**
	 * Constructor of instance
	 *
	 * Initialize of a session and write them to the $this->document property
	 *
	 * @param ?string $hash Hash of the session in ArangoDB
	 * @param ?int $expires Date of expiring of the session (used for creating a new session)
	 * @param array &$errors Registry of errors
	 *
	 * @return static
	 */
	public function __construct(?string $hash = null, ?int $expires = null, array &$errors = [])
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Initialized the collection

				if (isset($hash) && $document = $this->hash($hash, errors: $errors)) {
					// Found the instance of the ArangoDB document of session and received a session hash

					// Writing document instance of the session from ArangoDB to the property of the implementing object 
					$this->__document($document);
				} else if (static::VERIFICATION === verification::hash_else_address && $document = $this->address($_SERVER['REMOTE_ADDR'], errors: $errors)) {
					// Found the instance of the ArangoDB document of session and received a session hash

					// Writing document instance of the session from ArangoDB to the property of the implementing object 
					$this->__document($document);
				} else {
					// Not found the instance of the ArangoDB document of session

					// Initializing a new session and write they into ArangoDB
					$_id = document::write(
						static::COLLECTION,
						[
							'active' => true,
							'expires' => $expires ?? time() + 604800,
							'address' => $_SERVER['REMOTE_ADDR'],
							'x-forwarded-for' => $_SERVER['HTTP_X_FORWARDED_FOR'] ?? null,
							'referer' => $_SERVER['HTTP_REFERER'] ?? null,
							'useragent' => $_SERVER['HTTP_USER_AGENT'] ?? null
						]
					);

					if ($session = collection::execute(
						<<<'AQL'
							FOR d IN @@collection
								FILTER d._id == @_id && d.expires > @time && d.active == true
								RETURN d
						AQL,
						[
							'@collection' =>	static::COLLECTION,
							'_id' => $_id,
							'time' =>	time()
						],
						errors: $errors
					)) {
						// Found the instance of just created new session

						// Generating a hash and write into the instance of the ArangoDB document of session property
						$session->hash = sodium_bin2hex(sodium_crypto_generichash($_id));

						if (document::update($session, errors: $errors)) {
							// Update is writed to ArangoDB

							// Writing instance of the session document from ArangoDB to the property of the implementing object 
							$this->__document($session);
						} else throw new exception('Failed to write the session data');
					} else throw new exception('Failed to create or find just created session');
				}
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}
	}

	/**
	 * Search for a connected account
	 *
	 * @param array &$errors Registry of errors
	 *
	 * @return account|null An object implements the instance of the account document from ArangoDB, if found
	 */
	public function account(array &$errors = []): ?account
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				if (collection::initialize(connect::COLLECTION, connect::TYPE, errors: $errors)) {
					if (collection::initialize(account::COLLECTION, account::TYPE, errors: $errors)) {
						// Initialized collections

						// Search for connected account
						$result = collection::execute(
							<<<AQL
							FOR v IN INBOUND @session GRAPH sessions
								SORT v.created DESC
								LIMIT 1
								RETURN v  
							AQL,
							[
								'session' => $this->getId()
							],
							errors: $errors
						);

						if ($result instanceof _document) {
							// Found active settings

							// Initializing the object
							$account = new account;

							if (method_exists($account, '__document')) {
								// Object can implement a document from ArangoDB

								// Abstractioning of parameters
								$result->language = language::{$result->language} ?? 'en';

								// Writing the instance of account document from ArangoDB to the implement object
								$account->__document($result);

								// Exit (success)
								return $account;
							}
						} else return null;
					} else throw new exception('Failed to initialize ' . account::TYPE . ' collection: ' . account::COLLECTION);
				} else throw new exception('Failed to initialize ' . connect::TYPE . ' collection: ' . connect::COLLECTION);
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}

	/**
	 * Connect account to session
	 *
	 * @param account $account Account
	 * @param array &$errors Registry of errors
	 *
	 * @return string|null The identifier of the created edge of the "connect" collection, if created
	 */
	public function connect(account $account, array &$errors = []): ?string
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				if (collection::initialize(connect::COLLECTION, connect::TYPE, errors: $errors)) {
					if (collection::initialize(account::COLLECTION, account::TYPE, errors: $errors)) {
						// Collections initialized

						// The instance of the session document from ArangoDB is initialized?
						isset($this->document) || throw new exception('The instance of the sessoin document from ArangoDB is not initialized');

						// Writing document and exit (success)
						return document::write(
							connect::COLLECTION,
							[
								'_from' => $account->getId(),
								'_to' => $this->document->getId()
							],
							errors: $errors
						);
					} else throw new exception('Failed to initialize ' . account::TYPE . ' collection: ' . account::COLLECTION);
				} else throw new exception('Failed to initialize ' . connect::TYPE . ' collection: ' . connect::COLLECTION);
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}

	/**
	 * Search by hash
	 *
	 * Search for the session in ArangoDB by hash 
	 *
	 * @param string $hash Hash of the session in ArangoDB
	 * @param array &$errors Registry of errors
	 *
	 * @return _document|null instance of document of the session in ArangoDB
	 */
	public static function hash(string $hash, array &$errors = []): ?_document
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Collection initialized

				// Search the session data in ArangoDB
				return collection::execute(
					<<<'AQL'
					FOR d IN @@collection
						FILTER d.hash == @hash && d.expires > $time && d.active == true
						RETURN d
					AQL,
					[
						'@collection' => static::COLLECTION,
						'hash' => $hash,
						'time' => time()
					],
					errors: $errors
				);
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}

	/**
	 * Search by IP-address
	 *
	 * Search for the session in ArangoDB by IP-address 
	 *
	 * @param string $address IP-address writed to the session in ArangoDB
	 * @param array &$errors Registry of errors
	 *
	 * @return _document|null instance of document of the session in ArangoDB
	 */
	public static function address(string $address, array &$errors = []): ?_document
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Collection initialized

				// Search the session data in ArangoDB
				return collection::execute(
					<<<'AQL'
					FOR d IN @@collection
						FILTER d.address == @address && d.expires > @time && d.active == true
						RETURN d
					AQL,
					[
						'@collection' =>	static::COLLECTION,
						'address' => $address,
						'time' =>	time()
					],
					errors: $errors
				);
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}

	/**
	 * Write to buffer of the session
	 *
	 * @param array $data Data for merging
	 * @param array &$errors Registry of errors
	 *
	 * @return bool Is data has written into the session document from ArangoDB?
	 */
	public function write(array $data, array &$errors = []): bool
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Initialized the collection

				// The instance of the session document from ArangoDB is initialized?
				isset($this->document) || throw new exception('The instance of the sessoin document from ArangoDB is not initialized');

				// Writing data into buffer of the instance of the session document from ArangoDB
				$this->document->buffer = array_replace_recursive(
					$this->document->buffer ?? [],
					[$_SERVER['INTERFACE'] => array_replace_recursive($this->document->buffer[$_SERVER['INTERFACE']] ?? [], $data)]
				);

				// Writing to ArangoDB and exit (success)
				return document::update($this->document, errors: $errors);
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return false;
	}
}
