#!/usr/bin/php
<?php declare(strict_types=1);

namespace Kilo;

// -----------------------------------------------------------------------------
// ! App Constants
// -----------------------------------------------------------------------------
define('KILO_VERSION', '0.0.1');
define('KILO_TAB_STOP', 4);
define('KILO_QUIT_TIMES', 3);

// Log notices/errors/warnings to file
set_error_handler(static function (int $no, $str, $file, $line, $context) {
	$msg = print_r([
		'errno' => $no,
		'message' => $str,
		'file' => $file,
		'line' => $line,
		// 'context' => $context,
	], TRUE);
	file_put_contents('kilo.log', $msg, FILE_APPEND);

}, -1);

// Set up autoloading
require_once __DIR__ . '/src/functions.php';
require_once __DIR__ . '/src/hldb.php';
spl_autoload_register(static function ($class) {
	$parts = explode('\\', $class);
	$file = __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . $parts[1] . '.php';
	if (file_exists($file))
	{
		require_once $file;
	}
});

// ! Init with an IIFE
return (static function (int $argc, array $argv): int {
	enable_raw_mode();

	$editor = Editor::new();

	if ($argc >= 2)
	{
		$editor->open($argv[1]);
	}

	$editor->setStatusMessage('HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find');

	// Input Loop
	while (true)
	{
		$editor->refreshScreen();
		$char = $editor->processKeypress();
		if ($char === NULL)
		{
			break;
		}
	}

	return 0;
})($argc, $argv);