#include <ctime>
#include <sys/times.h>
#include "../rand/randomc.h"
#include "individual.h"
#include "random_solution.h"

using namespace std;

time_t random_solution::wall_pt = 0;
time_t random_solution::wall_tmr = 0;
double random_solution::process_pt = 0;
double random_solution::process_tmr = 0;
unsigned long random_solution::individuals = 0;

/**
 * counts the number of ticks recorded in a tms structure
 */
double random_solution::get_ticks(struct tms &p_tms) {
  return (p_tms.tms_utime + p_tms.tms_stime + p_tms.tms_cutime
      + p_tms.tms_cstime);
}

/**
 * sets the reference point of the stopwatch
 */
void random_solution::start_timer() {
  random_solution::wall_pt = time(0);

  struct tms tmp;
  times(&tmp);
  random_solution::process_pt = get_ticks(tmp);
}

/**
 * stops the stopwatch
 */
void random_solution::stop_timer() {
  random_solution::wall_tmr = time(0)
    - random_solution::wall_pt;

  struct tms tmp;
  times(&tmp);

  random_solution::process_tmr = get_ticks(tmp)
    - random_solution::process_pt;
}

/**
 * picks the best solution from a number of randomly
 * generated ones
 */
individual *random_solution::get_solution(char p_ind_type,
    int p_ind_size) {
  RANDOM_GENERATOR rg (time(0)); // defined in individual.h

  individual *best_ind = new individual (p_ind_type,
      p_ind_size, &rg);

  random_solution::individuals = 1;

  struct tms tmp;
  times(&tmp);
  double start_time = get_ticks(tmp);

  do {
    individual *tmp_ind = new individual (p_ind_type,
        p_ind_size, &rg);

    random_solution::individuals++;

    if(tmp_ind->get_fitness() > best_ind->get_fitness()) {
      delete best_ind;
      best_ind = tmp_ind;
    }
    else delete tmp_ind;

    times(&tmp);
  } while((get_ticks(tmp) - start_time)
      < random_solution::process_tmr);

  return best_ind;
}

