// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright The Music Player Daemon Project

#include "ncu.hxx"
#include "config.h"

#ifdef ENABLE_COLORS
#include "Styles.hxx"
#endif

#ifdef HAVE_GETMOUSE
#include "Options.hxx"
#endif

#include <curses.h>

#include <stdexcept>

#ifdef NCURSES_VERSION
#include <string.h>
#endif

static SCREEN *ncu_screen;

void
ncu_init()
{
	/* initialize the curses library */
	ncu_screen = newterm(nullptr, stdout, stdin);
	if (ncu_screen == nullptr)
		throw std::runtime_error{"Failed to initialize terminal"};

	/* initialize color support */
#ifdef ENABLE_COLORS
	ApplyStyles();
#endif

	/* Ctrl-C generates keycode 0x03 instead of SIGINT */
	raw();

	/* tell curses not to do NL->CR/NL on output */
	nonl();

	/* don't echo input */
	noecho();

	/* set cursor invisible */
	curs_set(0);

	/* enable extra keys */
	keypad(stdscr, true);

#ifdef NCURSES_VERSION
	/* define Alt-* keys which for some reasons aren't defined by
	   default (tested with ncurses 6.1 on Linux) */

	if (!key_defined("M-^@")) {
		char buffer[8];
		buffer[0] = 033;

		for (int i = 0x80; i <= 0xff; ++i) {
			const char *name = keyname(i);
			if (name != nullptr && name[0] == 'M' &&
			    name[1] == '-' && name[2] != 0 &&
			    (name[3] == 0 || name[4] == 0)) {
				strcpy(buffer + 1, name + 2);
				define_key(buffer, i);
			}
		}
	}
#endif

	/* initialize mouse support */
#ifdef HAVE_GETMOUSE
	if (options.enable_mouse)
		mousemask(ALL_MOUSE_EVENTS, nullptr);
#endif

	refresh();
}

void
ncu_deinit()
{
	endwin();

	delscreen(ncu_screen);
}
