// Billiger Beispielbot .. nur um reinzukommen :P

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "Messagetypes.h"

volatile double acceleration = 0.0;
volatile double robot_rotate = 0.0;
double radar_angle, rotate, brake;

message_to_robot_type name2msg(char* msg_name) {
  for (int i=0; message_to_robot[i].msg[0] != '\0'; i++) {
    if (strcmp(message_to_robot[i].msg, msg_name) == 0) return(message_to_robot_type)i;
  }
  return UNKNOWN_MESSAGE_TO_ROBOT;
}

void check_messages(int sig) {
  char msg_name[81];
  char msg_text[81];
  message_to_robot_type msg_t;

  cin.clear();
  while (!cin.eof()) {
    cin >> msg_name;
    msg_t = name2msg(msg_name);
    switch (msg_t) {
      case INITIALIZE:
        int init;
	cin >> init;
	if (init == 1) {
	  cout << "Name Rupert" << endl;
	  cout << "Colour dede11 de5500" << endl;
	}
        break;
      case ROTATION_REACHED:
	int what;
	cin >> what;
	if (what == 1) {
	  cout << "Accelerate 1.00" << endl;
	}
	break;
      case GAME_STARTS:
	acceleration = 0.5;
	cout << "Accelerate " << acceleration << endl;
	cout << "Sweep 6 " << M_PI/2.0 << " " << -M_PI/2.0 << " " << M_PI/2.0 << endl;
	break;
      case RADAR:
	double dist, energy;
	int object;

	cin >> dist >> object >> radar_angle;
	switch (object) {
	  case ROBOT:
	    cout << "Shoot 100" << endl;
	    break;
	  case COOKIE:
	    rotate = radar_angle;
	    robot_rotate = 0.0;
	    brake = 0.0;
	    if (dist > 7) { acceleration = 2.0; }
	    else if (dist > 5) { acceleration = 1.0; }
	    else if (dist < 2) { acceleration = 0.5; }
	    cout << "Rotate 1 " << robot_rotate << endl;
	    cout << "RotateAmount 1 " << M_PI << " " << rotate << endl;
	    cout << "Brake " << brake << endl;
	    cout << "Accelerate " << acceleration << endl;
	    break;
	  case WALL:
	    if (dist < 3) {
	      acceleration = 0.0;
	      rotate = -radar_angle;
	      cout << "RotateAmount 1 " << M_PI << " " << rotate << endl;
	      brake = 1.0;
	    } else if (dist < 5) {
	      rotate = -radar_angle/2;
	      acceleration = acceleration/2;
	      brake = 0.5;
	      cout << "RotateAmount 1 " << M_PI << " " << rotate << endl;
	    }
      	    cout << "Accelerate " << acceleration << endl;
	    cout << "Brake " << brake << endl;
	    break;
	  case MINE:
	    if (dist < 3) {
	      cout << "Shoot 1" << endl; 
	    }
	    break;
	}
	
	break;
      defauldt:
	break;
    }
  }
//  signal(sig, check_messages);
}

int main(int argc, char * argv[]) {
  sigset_t usr1set;

  //robot_rotate = 0.53;


  //check_messages(SIGUSR1);
  signal(SIGUSR1, check_messages);

  // libpthread seems to block USR1 sometimes for some reason
  sigemptyset(&usr1set);
  sigaddset(&usr1set, SIGUSR1);
  sigprocmask(SIG_UNBLOCK, &usr1set, NULL);


  cout << "RobotOption " << (int)SIGNAL << " " << (int)SIGUSR1 << endl;

  for(;;sleep(1)) {
  }
  return(EXIT_SUCCESS);
}

