
#include "user.h"

#include <String.h>

User::User (char* termtype, char* hostname) :
       os(cout),
       userWindow(stdscr)
//       userWindow(userWindow.lines(), userWindow.cols(), 0, 0)
{
  TermHd.userWindow = &userWindow;

  lessThan25 = (userWindow.lines() < 25);

//  isVT100 =  (fcompare(termtype,"vt100")==0) ? 1 : 0;
  isVT100 = 1;
  if(isVT100) dont_process_output =1;
  else        pTerm = & TermHd;
  
  readFD.Assign_fd(0);
  readFD.Param_add(CBREAK);
  readFD.Param_remove(ECHO);
  readFD.NonBlocking();
}

fd_set User::readfds ()
{
  fd_set fdset;
  FD_ZERO(&fdset);
  FD_SET(0,&fdset);
  return fdset;
}

int User::read (char* buf, int nchars)
{
  return ::read(0,buf,nchars);
}

int User::write (char* buf, int nchars)
{
  if (pTerm != &TermVTbart)
    for (int i = 0; i < nchars; i++) userWindow.addch(buf[i]);
  else
    pTerm->write(buf, nchars);
  receivedSomething += 1;
}

void User::write_ClearScreen()
{
  userWindow.clear();
  userWindow.move(0, 0);
  userWindow.touchwin();
  userWindow.refresh();

  workingMessageShown = 0;
}

void User::working_message()
{
    int x, y;

    userWindow.getyx(y, x);

    userWindow.move(userWindow.lines() - 1, 0);
    userWindow.clrtoeol();
    userWindow.move(userWindow.lines() - 1, userWindow.cols() / 2 - 5);
    userWindow.addstr("working...");

    userWindow.move(y, x);
    userWindow.refresh();

    workingMessageShown = 1;
    receivedSomething = 0;
}

void User::flush ()
{
    if (workingMessageShown) {
	if (receivedSomething > 25) {
	    int x, y;

	    // save the current cursor position
	    userWindow.getyx(y, x);

	    // move to the last line and clear it
	    userWindow.move(userWindow.lines() - 1, 0);
	    userWindow.clrtoeol();

	    // restore saved cursor position
	    userWindow.move(y, x);

	    // remember that the message is now not displayed
	    workingMessageShown = 0;
	}
    }

    // flush Curses window to the user for viewing
    userWindow.refresh();
}

void User::redraw ()
{
  userWindow.refresh();
}

void User::Person_is_VT100 (bool yes)
{
  isVT100 =yes;
  dont_process_output =0;
  if(isVT100) {
    if(recievingVT100) {
      if(recievingBarton && VTBartonHack_enabled) pTerm = &TermVTbart;
      else dont_process_output =1;
    }
    else dont_process_output =1; 
  }
  else {
    if(recievingVT100) {
      if(recievingBarton) pTerm = &TermHdbart;
      else                pTerm = &TermHd;
    }
    else dont_process_output =1;
  }
}
void User::Library_is_VT100 (bool yes)
{
  recievingVT100 = yes;
  Person_is_VT100(isVT100);
}
void User::Now_using_BARTON (bool p)
{
  recievingBarton =p;
  Person_is_VT100(isVT100);
}

void User::VTBartonHack_Enable (bool p)
{
  VTBartonHack_enabled = p;
  Person_is_VT100(isVT100);
}

