#include "AFMotor.h"
#include "IRremote.h"

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);

int RECV_PIN = 9;
IRrecv irrecv(RECV_PIN);
decode_results results;
int car_state;

void setup() {
  irrecv.enableIRIn(); // Start the receiver
  //turn on motor
  motor1.setSpeed(255);
  motor2.setSpeed(255);

  Serial.begin(9600);
  Serial.print("Ready");

  motor1.run(RELEASE);
  motor2.run(RELEASE);

}

int compare(unsigned int oldval, unsigned int newval) {
  if (newval < oldval * .8) {
    return 0;
  }
  else if (oldval < newval * .8) {
    return 2;
  }
  else {
    return 1;
  }
}

#define FNV_PRIME_32 16777619
#define FNV_BASIS_32 2166136261

unsigned long decodeHash(decode_results *results) {
  unsigned long hash = FNV_BASIS_32;
  for (int i = 1; i + 2 < results->rawlen; i++) {
    int value =  compare(results->rawbuf[i], results->rawbuf[i + 2]);
    // Add value into the hash
    hash = (hash * FNV_PRIME_32) ^ value;
  }
  return hash;
}

void loop() {

  if (irrecv.decode(&results)) {
    unsigned long hash = decodeHash(&results);

    switch (hash) {
      case 0xBB78C8E7: // Forward
        car_state = 1;

        Serial.println("Forward");
        break;
      case 0x8902E8AB: // Reverse
        car_state = 2;

        Serial.println("Reverse");
        break;
      case 0x4070260B: // Left
        car_state = 3;

        Serial.println("Left");
        break;
      case 0x7262C647: // Right
        car_state = 4;

        Serial.println("Right");
        break;
      case 0x20934FE3: // Stop
        car_state = 5;

        Serial.println("Stop");
        break;
      default:
        Serial.print("Unknown ");
        Serial.println(hash, HEX);
    }
    irrecv.resume(); // Resume decoding (necessary!)
  }
  if (car_state == 1 ) {
    Serial.println("Forward");
    motor1.run(FORWARD);
    motor2.run(FORWARD);
  }
  if (car_state == 2 ) {
    Serial.println("Reverse");
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
  }
  if (car_state == 3 ) {
    Serial.println("Left");
    motor1.run(BACKWARD);
    motor2.run(FORWARD);
    delay(200);
    motor1.run(RELEASE);
    motor2.run(RELEASE);
  }
  if (car_state == 4) {
    Serial.println("Right");
    motor1.run(FORWARD);
    motor2.run(BACKWARD);
    delay(500);
    motor1.run(RELEASE);
    motor2.run(RELEASE);
  }
  if (car_state == 5) {
    Serial.println("Stop");
    motor1.run(RELEASE);
    motor2.run(RELEASE);
  }
}