#include <Arduino.h>
#include "wiring_private.h"
#include "ledControl.h"
#include "waiting.h"

#define TIMER_MAGNIFICATION 4

void initLED() {
  TCCR1A = 0b00000010;
  TCCR1B = 0b00011011;
  ICR1 = 0x4ff;
  pinMode(PIN_TOUCH0, INPUT_PULLUP);
  pinMode(PIN_TOUCH1, INPUT_PULLUP);
  pinMode(PIN_TOUCH2, INPUT_PULLUP);
  pinMode(PIN_TOUCH3, INPUT_PULLUP);
}

void ledControl(long color) {
  byte red = color >> 16 & 0xff;
  byte green = color >> 8 & 0xff;
  byte blue = color & 0xff;
  ledControl(red, green, blue);
}

void ledControl(byte red, byte green, byte blue) {
  pinMode(PIN_LED_RED, OUTPUT);
  if (red == 0) {
    digitalWrite(PIN_LED_RED, LOW);
  } else if (red == 255) {
    digitalWrite(PIN_LED_RED, HIGH);
  } else {
    sbi(TCCR1A, COM1A1);
    OCR1A = red * TIMER_MAGNIFICATION;
  }

  analogWrite(PIN_LED_GREEN, green);
  analogWrite(PIN_LED_BLUE, blue);
}

bool buzzerControl(int index, int duration) {
  tone(PIN_BUZZER, FREQ[index - 48], duration);
  return waiting((unsigned long)duration);
}

void buzzerOff() {
  noTone(PIN_BUZZER);
}

bool isPushed(byte index) {
  return (getTouchState() == index);
}

byte getTouchState() {
  byte state = digitalRead(PIN_TOUCH0);
  state |= digitalRead(PIN_TOUCH1) << 1;
  state |= digitalRead(PIN_TOUCH2) << 2;
  state |= digitalRead(PIN_TOUCH3) << 3;
  return state;
}

byte getLightSensorValue() {
  int val = analogRead(PIN_SNS_LIGHT);
  return map(val, 0, 1023 + 1, 0, 100 + 1);
}

byte getSoundSensorValue() {
  int val = analogRead(PIN_SNS_SOUND);
  return map(val, 0, 1023 + 1, 0, 100 + 1);
}
