#include <Adafruit_NeoPixel.h>
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>

void update_clock();
void showpixel(float centerposf, int pixelwidth, unsigned long color);

RtcDS3231<TwoWire> Rtc(Wire);

#define PIN        6 // Which pin on the Arduino is connected to the NeoPixels?
const int NUMPIXELS = 83; // How many NeoPixels are attached to the Arduino?

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

unsigned long color_on, color_off, color_sec, color_min, color_hour, color_hour_over;

const float seconds2pixel = NUMPIXELS /60.0;

void setup() {
  Serial.begin(9600);
  Rtc.Begin();
  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)


  color_on = pixels.Color(0, 0, 255);
  color_off = pixels.Color(0, 0, 0);
  color_sec = pixels.Color(0, 255, 0);
  color_min = pixels.Color(0, 0, 255);
  color_hour = pixels.Color(255, 0, 0);
  color_hour_over = pixels.Color(128, 0, 0);

  pixels.fill(color_off);
  pixels.show();
  
}

int last_second = 0;
int second = 0;
int minute = 0;
int hour = 0;

void update_clock()
{
  if(last_second != second)
  {
  
    Serial.print("Now is -> ");
    Serial.print(hour);
    Serial.print(":");
    Serial.print(minute);
    Serial.print(":");  
    Serial.println(second);
    
    last_second = second;
    // first delete all ...
    pixels.fill(color_off);

    for(int pixel = 1; pixel < hour; pixel++)
    {
      showpixel(seconds2pixel  * pixel, 1,  color_hour_over);
    }
    showpixel(seconds2pixel  * hour, 3,  color_hour);
    showpixel(seconds2pixel  * minute, 5,  color_min);
    showpixel(seconds2pixel  * second, 3,  color_sec);
    

    pixels.show();   // Send the updated pixel colors to the hardware.
  }    
}

int pixel2numpixels(int pixel)
{
  if(pixel >= NUMPIXELS)
  {
    pixel = pixel - NUMPIXELS;
  }
  return pixel;
}


void showpixel(float centerposf, int pixelwidth, unsigned long color)
{
  int centerpixelpos = round(centerposf);
  int pixelcenter = round((float)pixelwidth/2.0);
  int pixelpos[pixelwidth] = {0};

  for(int pixel = 0; pixel < pixelwidth; pixel++)
  {
    int pixeloffset = pixel - pixelcenter;
    pixelpos[pixel] = pixel2numpixels(centerpixelpos + pixeloffset);
    Serial.println(pixelpos[pixel]);
    pixels.setPixelColor(pixelpos[pixel], color);
  }
}
  
RtcDateTime now;

void loop() {

  now = Rtc.GetDateTime();
  hour = now.Hour();
  minute = now.Minute();
  second = now.Second();

  //RtcTemperature temp = Rtc.GetTemperature();
  update_clock();

  
}
