/*
*  Author: as
*
*/

#include <termios.h>
#include <unistd.h> // read
#include <iostream>
using namespace std;

char getch(bool echoOn) {  // read char from stdin without waiting for return key
  char buf=0;
  struct termios old = {0};
  if (tcgetattr(0, &old) < 0) perror("tcgetattr");
  old.c_lflag &= ~ICANON;
  if (!echoOn) old.c_lflag &= ~ECHO;    // echo off
  old.c_cc[VMIN] = 1;
  old.c_cc[VTIME] = 0;
  if (tcsetattr(0, TCSANOW, &old) < 0) perror("tcsetattr ICANOW");
  if (read(0, &buf, 1) < 0) perror("read");
  old.c_lflag |= ICANON;
  old.c_lflag |= ECHO;     // echo on
  if (tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr TCSADRAIN");
  return buf;
}

char getChoice(const char *text, bool echoOn) {
  cout << text << " " ;
  cout.flush();
  return getch(echoOn);
}

int main() {
   char c;
   getChoice("Menue Demo, press any key to start! ", false);

   while (1) {
     system("clear");   // Unix
     // system("cls");  // Windows
     cout << " ---- Menue ----" << endl;
     cout << "1  item 1" << endl;
     cout << "2  item 2" << endl;
     cout << "0  exit" << endl;
     c = getChoice("Your choice (0-2):", true);
     switch (c) {
       case '1': cout << endl << "item 1" << endl;
               sleep(2);
               break;
       case '2': cout << endl << "item 2" << endl;
               sleep(2);
               break;
       case '0': cout << endl<< "bye" << endl;
               exit(0);
       default: cout << endl << c << ": wrong input" << endl;
                sleep(2);
     }  // switch
  } // while
}

