#include "replay_device.hpp"

#include "config.hpp"
#include "common.hpp"

#include <fstream>
#include <iostream>

void ReplayDevice::suspend()
{}

void ReplayDevice::wake_up()
{}

ReplayDevice::ReplayDevice()
{
  Config *conf = Config::get_instance();

  if (!conf->p_replay_read().empty()) {
    std::ifstream file((conf->p_var_data_dir() + conf->p_replay_read()).c_str());
    std::string str;

    if (!file)
      std::cout << "file not found" << (conf->p_var_data_dir() + conf->p_replay_read()) << std::endl;

    while (getline(file, str)) {

      std::string::size_type i = str.find(",");
      int time_sec = conv::atoi(str.substr(0, i));
      str = str.substr(i+1);

      i = str.find(":");
      int time_msec = conv::atoi(str.substr(0, i));
      str = str.substr(i+1);

      timespec t;
      t.tv_sec = time_sec;
      t.tv_nsec = time_msec;

      Input input(str);
      inputs.push(std::make_pair(t, input));
    }
    clock_gettime(0, &time_start);
  }

  std::cout << "read:" << inputs.size() << " commands to replay" << std::endl;
}

void ReplayDevice::run()
{
  Config *conf = Config::get_instance();
  Input_master *input_master = Input_master::get_instance();
  
  std::pair<timespec, Input> element;
  timespec tmp;

  while (true) {
    
    input_done_.signal();
    input_ready.wait();
    input_ready.reset();

    if (inputs.empty()) {
      std::cout << "warning, no more input to replay" << std::endl;
      ::sleep(1000);
    } else {
      element = inputs.front();
      inputs.pop();
    }

    if (!conf->p_benchmark()) {
      clock_gettime(0, &tmp);
      
      int sleep_time = ((element.first.tv_sec - (tmp.tv_sec-time_start.tv_sec))*1000 + 
			(element.first.tv_nsec - (tmp.tv_nsec-time_start.tv_nsec)/1000000));
      if (sleep_time > 0)
	sleep(sleep_time);
    }
    input = element.second;
  }
}

