// More Information on YouTube: https://youtu.be/DgFc94p_6Ow

#include <Adafruit_NeoPixel.h>
#include <EE33_EncoderButton.h>

#define PIXELS_PIN    12  // NeoPixel Pin
#define PIXELS_NUM    16  // NeoPixel Number

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXELS_NUM, PIXELS_PIN, NEO_GRB + NEO_KHZ800);

Button button(EXTERNAL_INTERRUPT_D3, 400);
Encoder encoder(EXTERNAL_INTERRUPT_D2, A6);

typedef enum LED_COLOR
{
	COLOR_RED = 0,
	COLOR_GREEN = 1,
  COLOR_BLUE = 2,

	COLOR_MIN = COLOR_RED,
	COLOR_MAX = COLOR_BLUE
};

int PixelIdx = 0;
int PixelColor = COLOR_RED;

void button_event(uint8_t click_count)
{
	switch (click_count)
	{
			case 1:
			{
         PixelColor = (PixelColor != COLOR_MAX)? PixelColor + 1 : COLOR_MIN;
			}
			break;
		
			default:
			break;
	}

  //clear pixel
  strip.clear();    

  //set pixel
  if (PixelColor == COLOR_RED)
    strip.setPixelColor(PixelIdx, strip.Color(255, 0, 0));

  if (PixelColor == COLOR_GREEN)
    strip.setPixelColor(PixelIdx, strip.Color(0, 255, 0));

  if (PixelColor == COLOR_BLUE)
    strip.setPixelColor(PixelIdx, strip.Color(0, 0, 255));

  //show pixel
  strip.show();
}

void encoder_event(ENCODER_RESULT event)
{
		switch (event)
		{
			case ENCODER_CLOCKWISE:
			{
         if (++PixelIdx == PIXELS_NUM)
         {
            PixelIdx = 0;
         }
			}
			break;
		
			case ENCODER_COUNTERCLOCKWISE:
			{
				 if (--PixelIdx < 0)
         {
            PixelIdx = PIXELS_NUM - 1;
         }
			}
			break;
		
			default:
			break;
		}

    //clear pixel
    strip.clear();    

    //set pixel
    if (PixelColor == COLOR_RED)
      strip.setPixelColor(PixelIdx, strip.Color(255, 0, 0));

    if (PixelColor == COLOR_GREEN)
      strip.setPixelColor(PixelIdx, strip.Color(0, 255, 0));

    if (PixelColor == COLOR_BLUE)
      strip.setPixelColor(PixelIdx, strip.Color(0, 0, 255));

    //show pixel
    strip.show();
}

void setup() {
  Serial.begin(115200);

  button.begin();
  encoder.begin();

  strip.begin();                                         // Intitialize NexoPixel Object

  PixelIdx = 0;                                          // Intitialize NexoPixel index
  PixelColor = COLOR_RED;                                // Intitialize NexoPixel Color

  strip.setPixelColor(PixelIdx, strip.Color(255, 0, 0)); //Set NexoPixel Color
  strip.show();                                          //Show NexoPixel 

}

void loop() {

	if (button.available())
	{
		button_event(button.read());
	}

	if (encoder.available())
	{
		encoder_event(encoder.read());	
	}
}