#include "../include/TTY.h"

namespace environment {
namespace tty {

  TTY::TTY (std::string  name,
	    Parameters * param)
  {
    this->name  = name;
    this->param = param;

    xtty = new xTTY [param->nb_tty];

    
    for (uint32_t i=0; i<param->nb_tty; i++)
      {
	// ***** Create a log_file *****
	xtty [i].log_file = fopen(param->name_tty[i].c_str(),"w");

	if (xtty [i].log_file == NULL)
	  {
	    // Error
	    std::cerr << "<Tty> Can't open the file : \"" << param->name_tty[i] << "\"" << std::endl;
	    exit(1);
	  }

	if (param->with_xtty == true)
	  {
	    // ***** TTY and pipe init *****
	    canal canal_output;
	    
	    if (pipe (canal_output.CanalPipe) != 0)
	      {
		std::cerr << "<Tty> Error in pipe creation" << std::endl;
		exit(1);
	      }
	      
	    if ((xtty[i].pid = fork()) == 0)
	      {
		// Childen -> transform in a xtty
		close(0); // s
		dup (canal_output.CanalPipe [0]);
		close(1);
		execlp("xtty","xtty", param->name_tty [i].c_str() ,NULL); // devient un tty
		
		std::cerr << "<Tty> Error in the creation of tty" << std::endl
			  << "Test if environment's variable $PATH is set with ${MORPHEO_TOPLEVEL}/IPs/systemC/Environment/TTY/xtty" << std::endl;
		exit (1);
	      }
	    else
	      {
		// father
		xtty[i].pipe_output = canal_output.CanalPipe [1];
	      }
	  }
      }//end for
  }

  TTY::~TTY (void)
  {
    // Kill all tty
    for (unsigned int i=0; i<param->nb_tty; i++)
      {
	if (param->with_xtty == true)
	  if (xtty[i].pid)
	    kill(xtty[i].pid,SIGTERM);
	fclose(xtty[i].log_file);
      }

    delete [] xtty;
  }

};
};
