<?php

declare(strict_types=1);

namespace mirzaev\deeproots\models;

// Files of the project
use mirzaev\deeproots\models\core,
  mirzaev\deeproots\models\question,
	mirzaev\deeproots\models\enumerations\language;

// 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;

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

/**
 * Answer
 *
 * @uses question
 * @package mirzaev\deeproots\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 answer extends core
{
	/**
	 * File
	 *
	 * @var string $database Path to the database file
	 */
	protected string $file = DATABASES . DIRECTORY_SEPARATOR . 'answers.baza';

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

	/**
	 * Constructor
	 *
	 * @param language $language Questions language
	 *
	 * @return void
	 */
	public function __construct()
	{
		// Initializing the database
		$this->database = new database()
			->encoding(encoding::ascii)
			->columns(
				new column('identifier', type::long_long_unsigned),
				new column('A', type::char),
				new column('B', type::char),
				new column('C', type::char),
				new column('D', type::char),
				new column('updated', type::integer_unsigned),
				new column('created', type::integer_unsigned)
			)
			->connect($this->file);
	}

	/**
	 * Create
	 *
	 * Creates the record in the database
	 *
	 * @param int $identifier Identifier (same for questions in every language)
	 * @param int $a Number of points for answer A
	 * @param int $b Number of points for answer B
	 * @param int $c Number of points for answer C
	 * @param int $d Number of points for answer D
	 *
	 * @return int|false The record identifier, if created
	 */
	public function create(?int $identifier, int $a = 0, int $b = 0, int $c = 0, int $d = 0): int|false
	{
		// Initializing the identifier
		$identifier ??= $this->database->count() + 1;

		// Initializing the record
		$record = $this->database->record(
			$identifier,
			$a,
			$b,
			$c,
			$d,
			svoboda::timestamp(),
			svoboda::timestamp()
		);

		// Creating the record in the database
		$created = $this->database->write($record);

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