<?php

declare(strict_types=1);

namespace mirzaev\huesos\controllers;

// Files of the project
use mirzaev\huesos\controllers\core;

// Framework for PHP
use mirzaev\minimal\http\enumerations\status;

/**
 * Controller of account
 *
 * @package mirzaev\huesos\controllers
 *
 * @param array $errors Registry of errors
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class account extends core
{
	/**
	 * Errors
	 *
	 * @var array $errors Registry of errors
	 */
	protected array $errors = [
		'session' => [],
		'account' => [],
		'buffer' => []
	];

	/**
	 * Write 
	 *
	 * Write to the buffer
	 *
	 * @param mixed ...$parameters Parameters for writing to the buffer
	 *
	 * @return null
	 *
	 * @todo переделать под trait buffer
	 */
	public function write(mixed ...$parameters): null
	{
		if (!empty($parameters) && isset($this->account)) {
			// Received parameters and initialized model with buffer trait

			// Declaring the buffer of deserialized parameters
			$deserialized = [];

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

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

				// Declaring the buffer of deserialized parameter
				$parameter = null;

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

				// Writing into the buffer of deserialized parameters
				$deserialized = array_merge_recursive($parameter, $deserialized);
			}

			// Write to the document from ArangoDB
			if (!empty($deserialized)) $this->account->write($deserialized, $this->errors['buffer']);

			// Writing status of response
			$this->response->status = status::created;
		}

		// Exit (success)
		return null;
	}

}
