/* ============================================
  code is placed under the MIT license
  Copyright (c) 2022 J-M-L
  For the Arduino Forum : https://forum.arduino.cc/u/j-m-l / https://forum.arduino.cc/t/finding-a-good-search-term/1311566?u=j-m-l

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  ===============================================
*/

#include <Wire.h>
#include <hd44780.h>                        // main hd44780 header
#include <hd44780ioClass/hd44780_I2Cexp.h>  // i2c expander i/o class header
#include <Toggle.h>

const uint8_t nbCols = 20;
const uint8_t nbRows = 2;
hd44780_I2Cexp lcd;

const byte cyclePin = 2;
const byte maintenanceDonePin = 3;
const byte alertPin = 4;
const byte alarmSilencePin = 6;

struct MaintenanceSchedule {
  const char * label;
  const uint16_t everyCycle;
  uint16_t countsToAlarm;
  bool needsMaintenance;
  bool alarmSilenced;
  bool dataChanged;
};

MaintenanceSchedule parts[] = {
  {"Pusher",  3, 0, false, true, false},   // maintain every 7 cycles
  {"Rocker", 5, 0, false, true, false}, // maintain every 10 cycles
  {"Plate",  8, 0, false, true, false},  // maintain every 3 cycles
  {"Zerks",  9, 0, false, true, false},   // maintain every 2 cycles
  {"Cylinder", 14, 0, false, true, false}    // every 14 cycles
};

// ----------------------

const uint32_t partsCnt = sizeof parts / sizeof * parts;
uint32_t partsNeedingMaintenanceCnt = 0;


Toggle cycleButton;
Toggle maintenanceDoneButton;

uint32_t cycleCounter = 0;
uint16_t nextAlarmIn = 0;
char txtBuffer[3 * nbCols + 1];


void saveState() {
  // calls to eeprom would go here
}

void blinkAlertIfNeeded() {
  static unsigned long lastBlink;
  if (partsNeedingMaintenanceCnt != 0) {
    if (millis() - lastBlink >= 200) {
      digitalWrite(alertPin, digitalRead(alertPin) == LOW ? HIGH : LOW);
      lastBlink = millis();
    }
  } else digitalWrite(alertPin, LOW);
}

void showCycles() {
  snprintf(txtBuffer, sizeof txtBuffer, "%8lu", cycleCounter);
  lcd.setCursor(nbCols - 8, 0);
  lcd.print(txtBuffer);
}

void showMaintenanceList() {
  partsNeedingMaintenanceCnt = 0;
  txtBuffer[0] = '\0';
  for (auto &p : parts ) {
    if (p.needsMaintenance) {
      partsNeedingMaintenanceCnt++;
      p.alarmSilenced = false;
      if (*txtBuffer != '\0') strlcat(txtBuffer, ", ", sizeof txtBuffer);
      strlcat(txtBuffer, p.label, sizeof txtBuffer);
      break; // placement here limits to one item displayed
    }
    // break won't work here
  }

  // erase
  for (byte r = 1; r < nbRows; r++) {
    lcd.setCursor(0, r);
    for (byte c = 0; c < nbCols; c++) lcd.write((' '));
  }

  // show the parts on the LCD. can span multiple lines. we have only nbRows-1 to play with
  int line = 1;
  int col = 0;

  lcd.setCursor(col, line);
  for (int i = 0; txtBuffer[i] != '\0'; ++i) {
    lcd.write(txtBuffer[i]);
    col++;

    // When reaching the maximum number of columns, move to the next line
    if (col >= nbCols) {
      col = 0;
      line++;
      if (line > nbRows - 1) {
        break;
      } else {
        lcd.setCursor(col, line);
      }
    }
  }

  // show counts to next alarm
  /*nextAlarmIn = 0;
  int top = 200;
  for (auto &p : parts ) {
    if ((p.everyCycle - p.countsToAlarm) < top)
      nextAlarmIn = p.everyCycle - p.countsToAlarm;
  }
*/
lcd.setCursor(0, 0);
lcd.print(txtBuffer);


// show number of alarms pending and number of items
//snprintf(txtBuffer, sizeof txtBuffer, "%03lu/%lu", partsNeedingMaintenanceCnt, partsCnt);
//lcd.setCursor(0, 0);
//lcd.print(txtBuffer);
} // end of showmaintenancelist

void setup() {
  pinMode(alertPin, OUTPUT);
  pinMode(alarmSilencePin, OUTPUT);
  cycleButton.begin(cyclePin);
  maintenanceDoneButton.begin(maintenanceDonePin);

  Serial.begin(115200);

  int result = lcd.begin(nbCols, nbRows);
  if (result) {
    Serial.print("LCD initialization failed: ");
    Serial.println(result);
    hd44780::fatalError(result);
  }

  lcd.print("PARTS SAVER 1.0");
  delay(1000);
  lcd.clear();
  showCycles();
  showMaintenanceList();
}

void loop() {
  cycleButton.poll();
  if (cycleButton.onPress()) {
    cycleCounter++;
    saveState(); //only save every ten cycles - to preserve eeprom
    showCycles();
    for (auto &p : parts ) {
      p.countsToAlarm++;
      if (cycleCounter % p.everyCycle == 0) {
        p.needsMaintenance = true;
        showMaintenanceList();
        // break; won't work here
      }
    }
  
  }

  maintenanceDoneButton.poll();
  if (maintenanceDoneButton.onPress()) {
    for (auto &p : parts )
      if (p.alarmSilenced == false)

      { p.needsMaintenance = false;
        p.alarmSilenced = true;
      }


    showMaintenanceList();
    saveState();
  }

  blinkAlertIfNeeded();
} // end of loop