#include <FastLED.h>

//#include <FastLED.h>

#define LED_PIN     3
#define NUM_LEDS    4
#define BRIGHTNESS  255
#define LED_TYPE    WS2812
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];
int downTime = 0;
int toggle = 0;
#define UPDATES_PER_SECOND 100


int analogPin = 10;        
int val = 0; 
int mode = 0;
int lastMode = -1;
int pressed = 0;
int LEDChange = 3;
int LEDSpeed = 10;

DEFINE_GRADIENT_PALETTE (violet) {
  0  , 0 , 211  , 255,
  73 , 146, 250  , 255,
  190, 117, 133, 100,
  255, 0 , 211  , 255,
}; 

DEFINE_GRADIENT_PALETTE (orange) {
  0  , 255, 172, 0 ,
  73 , 255, 240, 44,
  190, 255, 103, 36,
  255, 255, 172, 0,
};

DEFINE_GRADIENT_PALETTE (red) {
  0  , 255, 0, 0 ,
  110 , 96, 24, 24,
  140, 96, 24, 24,
  255, 255, 0, 0 ,
};

DEFINE_GRADIENT_PALETTE (black) {
  0    , 0, 0, 0 ,
  64   , 0, 0, 0 ,
  128  , 0, 0, 0 ,
  255  , 0, 0, 0 ,
};

CRGBPalette16 currentPalette;
CRGBPalette16 VioletPal = violet;
CRGBPalette16 OrangePal = orange;
CRGBPalette16 RedPal = red;
CRGBPalette16 BlackPal = black;

void setup() {
  Serial.begin(9600);           //  setup serial
  pinMode(0, OUTPUT);
  digitalWrite(0, HIGH);
  
  delay( 2000 ); // power-up safety delay
  
  FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(  BRIGHTNESS );
  
  currentPalette = RainbowColors_p;
}

void loop() {
  
  val = analogRead(analogPin);  // read the input pin
  if ((val < 100) and (pressed == 0) and (val > 5)) {
    if (analogRead(analogPin) < 100) { mode = mode + 1;}
    pressed = 1;
    
    if (mode > 5) {mode = 0;}
  }
  else if ((val > 300) and (val < 1000)) {
    pressed = 0;
    
  }
    Serial.println(val);          // debug value
  
    ChangePalette();
    static uint8_t startIndex = 0;
    startIndex = startIndex + 1; /* motion speed */
    
    FillLEDsFromPaletteColors( startIndex);
    
    FastLED.show();
    FastLED.delay(LEDSpeed);
}

void ChangePalette()
{
    if( lastMode != mode) {
        lastMode = mode;
        if( mode == 0)  { currentPalette = RainbowColors_p; LEDChange = 16; LEDSpeed = 30;}
        if( mode == 1)  { currentPalette = VioletPal;       LEDChange = 64; LEDSpeed = 10;}
        if( mode == 2)  { currentPalette = OrangePal;       LEDChange = 64; LEDSpeed = 10;}
        if( mode == 3)  { currentPalette = RedPal;          LEDChange = 3; LEDSpeed = 10;}
        if( mode == 4)  { currentPalette = BlackPal;          LEDChange = 0; LEDSpeed = 10;}
        if( mode == 5)  { currentPalette = RainbowColors_p; LEDChange = 64; LEDSpeed = 30;}
    }
}

void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
    uint8_t brightness = 255;
    
    for( int i = 0; i < NUM_LEDS; ++i) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, LINEARBLEND);
        colorIndex += LEDChange;
    }
}
