#include "cKeyboard.h"
#include <unistd.h> // read()

/** constructor of the keyboard object */
cKeyboard::cKeyboard(){

	tcgetattr( 0, &initial_settings );
	new_settings = initial_settings;
	new_settings.c_lflag &= ~ICANON;
	new_settings.c_lflag &= ~ECHO;
	new_settings.c_lflag &= ~ISIG;
	new_settings.c_cc[VMIN] = 1;
	new_settings.c_cc[VTIME] = 0;
	tcsetattr( 0, TCSANOW, &new_settings );
	peek_character=-1;
}

/** destructor of the keyboard object */
cKeyboard::~cKeyboard(){

    tcsetattr(0, TCSANOW, &initial_settings);
}

/**
 * check if a new key was hit and is in the buffer to read
 * @return 1 if a key was hit and is in the buffer to read, else 0
 */
int cKeyboard::kbhit(){

	unsigned char ch;
	int nread;

	if ( peek_character != -1 ){
		return 1;
	}
	new_settings.c_cc[VMIN]=0;
	tcsetattr( 0, TCSANOW, &new_settings );
	nread = read(0,&ch,1);
	new_settings.c_cc[VMIN]=1;
	tcsetattr( 0, TCSANOW, &new_settings );

	if ( nread == 1 ){
		peek_character = ch;
		return 1;
	}
	return 0;
}

/**
 * returns an character from the keyboard buffer
 * @return the readed character
 */
int cKeyboard::getch(){
	char ch;

	if ( peek_character != -1 ){
		ch = peek_character;
		peek_character = -1;
	} else {
		read( 0, &ch ,1 );
	}

	return ch;
}
