#include "user.h"
#include <iostream>
#include <termios.h>
#include <string>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

void
setEcho(bool echo) {
 struct termios t;

 //get the current settings
 tcgetattr(STDIN_FILENO, &t);

 //toggle echo
 if(echo)
   t.c_lflag = t.c_lflag | ECHO;
 else
   t.c_lflag = t.c_lflag & ~ECHO;

 //set the settings
 tcsetattr(STDIN_FILENO, TCSANOW, &t);
}


void
setBlocking(bool block) {
 struct termios t;

 //get the current settings
 tcgetattr(STDIN_FILENO, &t);

 //toggle blocking
 if(block)
   t.c_lflag = t.c_lflag | ICANON;
 else
   t.c_lflag = t.c_lflag & ~ICANON;

 //set the settings
 tcsetattr(STDIN_FILENO, TCSANOW, &t);
}


bool
hasInput() {
 fd_set fs;
 timeval tv;
 int i;

 //set up the fd set
 FD_SET(STDIN_FILENO, &fs);

 //set up the timespec
 tv.tv_sec = 0;
 tv.tv_usec = 1;

 //select
 i=select(STDIN_FILENO + 1, &fs, NULL, NULL, &tv);

 //0 no input  available
 //-1  error
 if(i==0 || i==-1) {
   return false;
 }

 //there is input
 return true;

}


void
clearStdin()  {
 while(hasInput())
   cin.get();
}