/*
 * Color Chooser
 *
 * The application let's you explore the colorspace of the Meggy Jr RGB. Move the cursor below the 
 * red/green/blue indicator to select one of the color components. If you press up or down you can
 * modify the intensity of the selected color component. Notice how the intensity bar on the left 
 * changes to visualize the color component's value. Everytime you change a value or press button 
 * A the current red/green/blue values are send over the serial to the computer so you can reuse 
 * that specific color in other applications.
 *
 * Written by Michael Olp <michael.olp@quixotic-project.de>
 * URL: http://www.quixotic-project.de/
 */

#include <MeggyJrSimple.h>

// values for rgb
byte rgb[3];
// points to the currently selected component in the rgb array
byte current;

// last time the cursor was set on or off
long cursor;
// millis how long the cursor waits till it turns on or off
long cursorBlink = 150;
byte cursorColor = 15;

void setup(){
  MeggyJrSimpleSetup();
  
  // init serial connection
  Serial.begin(9600);
  
  // init rgb values
  rgb[0] = 7;
  rgb[1] = 4;
  rgb[2] = 1;
  current = 1;
  
  EditColor(16, rgb[0], rgb[1], rgb[2]);
  
  // init cursor
  cursor = millis();
}

void loop(){
  ClearSlate();
  
  CheckButtonsPress();
  
  if(Button_Up){
    // increase the amount of red, green and blue depending on where the cursor stands
    if(rgb[current] < 15){
      rgb[current] = rgb[current] + 1;
    }
    printColor();
  }
  if(Button_Down){
    // decrease the amount of red, green and blue depending on where the cursor stands
    if(rgb[current] > 0){
      rgb[current] = rgb[current] - 1;
    }
    printColor();
  }
  if(Button_Left){
    if(current > 0){
      current--;
    }
  }
  if(Button_Right){
    if(current < 2){
      current++;
    }
  }
  if(Button_A){
    printColor();
  }
  if(Button_B){
  }
  
  // calculate and draw cursor
  if((millis() - cursor) >= cursorBlink){
    cursor = millis();
    if(cursorColor == 15){
      cursorColor = 0;
    } else{
      cursorColor = 15;
    }
  }
  // draw the cursor
  DrawPx(3 + current, 0, cursorColor);
  
  // calculate the new color
  EditColor(16, rgb[0], rgb[1], rgb[2]);
  
  // draw rgb dots
  DrawPx(3,1,Red);
  DrawPx(4,1,Green);
  DrawPx(5,1,Blue);
  
  // draw colorfield
  byte i,j;
  for(i = 3; i <= 5; i++){
    for(j = 4; j <= 6; j++){
      DrawPx(i, j, 16);
    } 
  }
  
  // display intensity
  for(i=0; i < (rgb[current] >> 1); i++){
    DrawPx(0, i, 3);
  }
  if(rgb[current] % 2 == 1){
    DrawPx(0, i, 10);
  } 
    
  // swap backbuffer ;)
  DisplaySlate();
}

void printColor(){
  Serial.print("rgb=");
  Serial.print(rgb[0], DEC);
  Serial.print(", ");
  Serial.print(rgb[1], DEC);
  Serial.print(", ");
  Serial.println(rgb[2], DEC);
}

