<?php

declare(strict_types=1);

namespace mirzaev\arming_bot\controllers;

// Files of the project
use mirzaev\arming_bot\controllers\core,
	mirzaev\arming_bot\models\session,
	mirzaev\arming_bot\models\account as model;

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

/**
 * Controller of account
 *
 * @package mirzaev\arming_bot\controllers
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class account extends core
{
	/**
	 * Registry of errors
	 */
	protected array $errors = [
		'session' => [],
		'account' => []
	];

	/**
	 * Write to the buffer
	 *
	 * @param array $parameters Parameters of the request (POST + GET)
	 *
	 * @return void
	 */
	public function write(array $parameters = []): void
	{
		if (!empty($parameters) && $this->account instanceof model) {
			// Found data of the program and active account

			foreach ($parameters as $name => $value) {
				// Iterate over parameters

				// Validation of the parameter
				if (mb_strlen($value) > 4096) continue;

				// Convert name to multidimensional array
				foreach (array_reverse(explode('_', $name)) as $key) $parameter = [$key => $parameter ?? json_validate($value) ? json_decode($value, true, 10) : $value];

				// Write data of to the buffer parameter in the implement object of account document from ArangoDB
				$this->account->buffer = $parameter + $this->account->buffer ?? [];
			}

			// Write from implement object to account document from ArangoDB
			document::update($this->account->__document(), $this->errors['account']);
		}
	}
}
