/* ============================================
  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 = 4;
hd44780_I2Cexp lcd;

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

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

MaintenanceSchedule parts[] = {
  {"Joint",  7, false},     // maintain every 7 cycles
  {"Gripper", 10, false},   // maintain every 10 cycles
  {"Vacuum",  5, false},    // maintain every 3 cycles
  {"Motor",  3, false},     // maintain every 2 cycles
};

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

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

Toggle cycleButton;
Toggle maintenanceDoneButton;

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


void saveState() {

}

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, "%08lu", cycleCounter);
  lcd.setCursor(nbCols - 8, 0);
  lcd.print(txtBuffer);
}

void showMaintenanceList() {
  partsNeedingMaintenanceCnt = 0;
  txtBuffer[0] = '\0';
  for (auto &p : parts ) {
    if (p.needsMaintenance) {
      partsNeedingMaintenanceCnt++;
      if (*txtBuffer != '\0') strlcat(txtBuffer, ", ", sizeof txtBuffer);
      strlcat(txtBuffer, p.label, sizeof txtBuffer);
    }
  }

  // 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);
      }
    }
  }


  snprintf(txtBuffer, sizeof txtBuffer, "%03lu/%lu", partsNeedingMaintenanceCnt, partsCnt);
  lcd.setCursor(0, 0);
  lcd.print(txtBuffer);
}

void setup() {
  pinMode(alertPin, 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();
    showCycles();
    for (auto &p : parts ) {
      if (cycleCounter % p.everyCycle == 0) {
        p.needsMaintenance = true;
        showMaintenanceList();
      }
    }
  }

  maintenanceDoneButton.poll();
  if (maintenanceDoneButton.onPress()) {
    for (auto &p : parts ) p.needsMaintenance = false;
    showMaintenanceList();
    saveState();
  }

  blinkAlertIfNeeded();
}