<?php

use Fernando\MyDB\Parser;
use Fernando\MyDB\Cli\App;
use Fernando\MyDB\Cli\Color;

require_once __DIR__ . '/vendor/autoload.php';

$parser = new Parser();
$cli = new App;
$printer = $cli->GetPrinter();

$cli->Register("help", function () use ($cli, $printer) {
	$txt = Color::Fg(45, 'Usage: php mydb [command] [options]'). PHP_EOL;
    $txt .= 'Available commands:'. PHP_EOL;

    foreach ($cli->GetAllCmds() as $i => $item) {
        $txt .= ' - ' . Color::Fg(10, $i) . PHP_EOL;
        unset($item);
    }

    $printer->Display(trim($txt));
});

$cli->Register("init", function () use ($cli, $printer) {
	$printer->Clear();
	$printer->display(Color::Fg(82, "Initializing..."));

	mkdir(__DIR__ . '/db');

	$printer->Display(Color::Fg(82, "Initialized successfully."));
});


$cli->Register("query", function () use ($printer, $parser) {
	$printer->newLine();
	$printer->out(Color::Fg(82, "Enter your file: "));
	$file = $printer->Read();

	if (is_file($file)) {
		$data = file_get_contents($file);
		$parser->parserAndInterpreter($data);
		exit();
	}

	$printer->Display(Color::Fg(82, "File not found '{$file}'."));
});

$cli->Register('exec', function () use ($printer, $parser) {
	$printer->Clear(); // Clear the screen

	while (true) {
		$input = readline("mydb > ");
	
		if ($input == "exit") {
			$printer->newLine();
			$printer->out(Color::Fg(99, "Bye!"));
			break;
		}
		
		if (in_array($input, ["", " "])) {
			continue;
		}
	
		$printer->newLine();

		$init = microtime(true);
		$parser->parserAndInterpreter($input);
		$end = microtime(true);
	
		$seconds = number_format($end - $init, 5);
		$printer->newLine();
		$printer->Display(Color::Fg(82, "Executed in {$seconds} seconds."));
	}

});


$cli->Run($argv);

