/*
 * This file is part of the Amalthea library.
 * Copyright (C) 2018-2020, 2024, 2026 Eugene 'Vindex' Stulin
 * Distributed under the BSL 1.0 or the GNU LGPL 3.0 or later.
 */

/**
 * Some simple functions for TTY.
 */
module amalthea.terminal;

public import amalthea.libcore;

import std.file;
import std.conv;
import std.stdio;


/*******************************************************************************
 * Colors of foreground.
 */
enum FGColor {
    black      = "\033[30m",    dark_gray     = "\033[90m",
    red        = "\033[31m",    light_red     = "\033[91m",
    green      = "\033[32m",    light_green   = "\033[92m",
    yellow     = "\033[33m",    light_yellow  = "\033[93m",
    blue       = "\033[34m",    light_blue    = "\033[94m",
    magenta    = "\033[35m",    light_magenta = "\033[95m",
    cyan       = "\033[36m",    light_cyan    = "\033[96m",
    light_gray = "\033[37m",    white         = "\033[97m",

    reset = "\033[0m",
    empty = ""
}


/*******************************************************************************
 * Output of color text.
 */
void cwrite(S...)(S args) {
    File f = stdout;
    static if (is(typeof(args[0]) == File)) {
        f = args[0];
    }
    string text;
    FGColor lastColorMark;
    foreach(i, arg; args) {
        static if (is(typeof(arg) == FGColor)) {
            lastColorMark = arg;
            text ~= cast(string)(arg);
        } else static if (!is(typeof(arg) == File)) {
            text ~= to!string(arg);
        }
    }
    f.write(text);
    if (lastColorMark != FGColor.empty)
        f.write(cast(string)FGColor.reset);
    f.flush();
}


/*******************************************************************************
 * Output of color text with line ending.
 */
void cwriteln(S...)(S args) {
    cwrite(args, "\n");
}


private extern(C) int isatty(int);

/*******************************************************************************
 * Wrapper for `isatty` (see: `man isatty`).
 * Tests whether a file descriptor refers to a terminal.
 * Params:
 *     f = File object. Usually, it is equal to stdout, stderr or stdin.
 */
bool isTTY(File f = stdout) {
    return cast(bool)isatty(f.fileno);
}
alias isTerminal = isTTY;


/*******************************************************************************
 * This function clears current terminal screen.
 */
void clearScreen() {
    write("\033[H\033[2J");
}

