/**
 Curses module.
*/

#include "libxi.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/time.h>
#include <inttypes.h>
#include <curses.h>

#include <gc.h>
#define WORDSIZE 8

void XI(initCurses_p)(void) {
    initscr();
    keypad(stdscr, TRUE);
}

void XI(destroyCurses_p)(void) {
    delwin(stdscr);
    endwin();
}

void XI(showCursor_pb)(xibool enabled) {
    curs_set(enabled ? 1 : 0);
}

xiint XI(getWindowSize_t2ii)(void) {
    int x, y;
    xiint x_, y_;
    getmaxyx(stdscr, y, x);
    x_ = x; y_ = y;
    SET2NDRESULT(y_);
    return x_;
}

xiint XI(getCursorPosition_t2ii)(void) {
    int x, y; xiint x_, y_;
    getyx(stdscr, y, x);
    x_ = x; y_ = y;
    SET2NDRESULT(y_);
    return x_;
}

void XI(moveCursor_pii)(xiint x, xiint y) {
    move(y, x);
}

void XI(echoKeys_pb)(xibool enable) {
    if (enable) {
        echo();
    } else {
        noecho();
    }
}

void XI(clearWindow_p)(void) {
    clear();
}

void XI(refreshWindow_p)(void) {
    refresh();
}

void XI(inputTimeout_pi)(xiint delay) {
    timeout(delay);
}

xiint XI(getInputChar_i)(void) {
    return getch();
}

xistring XI(getInputString_aii)(xiint maxlength) {
    char str[maxlength + 1];
    getnstr(str, maxlength);
    return mkString(str);
}

void XI(putChar_pi)(xiint c) {
    addch(c);
}

void XI(putString_pai)(xistring str) {
    int c;
    int len = str[-1];
    char string[len];
    for (c = 0; c < len; ++c)
        string[c] = str[c];
    addnstr(string, len);
}

void XI(deleteChar_p)(void) {
    delch(); 
}

xiint XI(readChar_i)(void) {
    return inch();
}

void XI(putCharAt_piii)(xiint c, xiint x, xiint y) {
    mvaddch(y, x, c);
}

void XI(putStringAt_paiii)(xistring str, xiint x, xiint y) {
    int c;
    int len = str[-1];
    char string[len];
    for (c = 0; c < len; ++c)
        string[c] = str[c];
    mvaddnstr(y, x, string, len);
}

void XI(deleteCharAt_pii)(xiint x, xiint y) {
    mvdelch(y, x);
}

xiint XI(readCharAt_iii)(xiint x, xiint y) {
    return mvinch(y, x);
} 

xiint XI(KEYUP_i)(void) { return KEY_UP; }
xiint XI(KEYDOWN_i)(void) { return KEY_DOWN; }
xiint XI(KEYLEFT_i)(void) { return KEY_LEFT; }
xiint XI(KEYRIGHT_i)(void) { return KEY_RIGHT; }

// kate: indent-width 4; replace-tabs on; tab-width 4; space-indent on;
// vim: sw=4 ts=4 et
