<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models;

// Files of the project
use kodorvan\neurobot\models\core,
	kodorvan\neurobot\models\message;

// Svoboda time
use svoboda\time\statement as svoboda;

// Baza database
use mirzaev\baza\database,
	mirzaev\baza\column,
	mirzaev\baza\record,
	mirzaev\baza\enumerations\encoding,
	mirzaev\baza\enumerations\type;

// Active Record pattern
use mirzaev\record\interfaces\record as record_interface,
	mirzaev\record\traits\record as record_trait;

// Library for neural networks support
use mirzaev\neuroseti\network;

// Built-in libraries
use Exception as exception,
	RuntimeException as exception_runtime;

/**
 * Chat
 *
 * @package kodorvan\neurobot\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 chat extends core implements record_interface
{
	use record_trait;

	/**
	 * File
	 *
	 * @var string $database Path to the database file
	 */
	protected string $file = DATABASES . DIRECTORY_SEPARATOR . 'chats.baza';

	/**
	 * Database
	 *
	 * @var database $database The database
	 */
	public protected(set) database $database;

	/**
	 * Serialized
	 *
	 * @var bool $serialized Is the implementator object serialized?
	 */
	private bool $serialized = true;

	/**
	 * Constructor
	 *
	 * @method record|null $record The record
	 *
	 * @return void
	 */
	public function __construct(?record $record = null)
	{
		// Initializing the database
		$this->database = new database()
			->encoding(encoding::utf8)
			->columns(
				new column('identifier', type::long_long_unsigned),
				new column('account', type::long_long_unsigned),
				new column('network', type::string, ['length' => 64]),
				new column('active', type::char),
				new column('updated', type::integer_unsigned),
				new column('created', type::integer_unsigned)
			)
			->connect($this->file);

		// Initializing the record
		$record instanceof record and $this->record = $record;
	}

	/**
	 * Write
	 *
	 * @param int $account The account identifier
	 * @param network $network The neural network
	 * @param bool $active Is the chat active?
	 *
	 * @return int|false The record identifier, if created
	 */
	public function write(
		int $account,
		network $network,
		bool $active = true
	): int|false {
		$record = $this->database->record(
			$this->database->count() + 1,
			$account,
			$network->name,
			(int) $active,
			svoboda::timestamp(),
			svoboda::timestamp()
		);

		// Writing the record into the database
		$created = $this->database->write($record);

		// Exit (success)
		return $created ? $record->identifier : false;
	}

	/**
	 * Serialize
	 *
	 * @return self The instance from which the method was called (fluent interface)
	 */
	public function serialize(): self
	{
		if ($this->serialized) {
			// The record implementor is serialized

			// Exit (fail)
			throw new exception_runtime('The record implementator object is already serialized');
		}

		// Serializing the record parameters
		if ($this->record->network instanceof network) $this->record->network = $this->record->network->name;
		$this->record->active = (int) $this->record->active;

		// Writing the serializing status
		$this->serialized = true;

		// Exit (success)
		return $this;
	}

	/**
	 * Deserialize
	 *
	 * @return self The instance from which the method was called (fluent interface)
	 */
	public function deserialize(): self
	{
	if (!$this->serialized) {
			// The record implementor is deserialized

			// Exit (fail)
			throw new exception_runtime('The record implementator object is already deserialized');
	}

		// Deserializing the record parameters
		if (is_string($this->record->network)) $this->record->network = network::{$this->record->network} ?? NETWORK_DEFAULT;
		$this->record->active = (bool) $this->record->active;

		// Writing the serialized status
		$this->serialized = false;

		// Exit (success)
		return $this;
	}

	/**
	 * Read last messages
	 *
	 * Search for records in the database
	 *
	 * @throws if not initialized the record
	 *
	 * @param array $from Messages senders
	 * @param bool $system Include system messages?
	 * @param int $amount Amount of messages
	 *
	 * @return array|false The found records array
	 */
	public function messages(array $from = [], bool $system = false, int $amount = 10): array|false
	{
		if ($this->record instanceof record) {
			// Initialized the record

			// Reading from the database
			return new message()->database->read(
				filter: fn(record $record) => 
				$record->chat === $this->identifier 
				&& array_search($record->from, $from, true) !== false
				&& ($system || (!$system && $record->system === 0)),
				amount: $amount,
				offset: 0
			);
		} else {
			// Not initialized the record

			// Exit (fail)
			throw new exception_runtime('Not initialized the record');
		}

		// Exit (fail)
		return false;
	}
}
