/* ============================================
  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.
  ===============================================
*/

/* Attempt to override total counts and parts needing service
  to enable two full lines for part name when alarmed
  operational changes:
  1. // disable display of parts needing maintenance and total number of parts
  2. cycle counter modulo save added
  3. start lcd print on line 0
  4. added edit mode switching - seems to work in this very basic mode
  5. including md encoder, no instance, causes no issues
  6. instantiated encoder and encoder pb, no issues
*/

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

const uint8_t nbCols = 20;
//const uint8_t nbRows = 2;
const uint8_t nbRows = 2; // using 2-line display
hd44780_I2Cexp lcd;

const byte encoderCLK = A0;
const byte encoderDT = A1;
const byte encoderSW = A2;
int encoderCnt = 0;
MD_REncoder theEncoder = MD_REncoder(encoderCLK, encoderDT);

const byte cyclePin = 2;
const byte maintenanceDonePin = 3;
const byte alertPin = 4;
bool doneButtonTrigger = false; // start in run mode

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

MaintenanceSchedule parts[] = {
  {"Case Pusher",  3, false},     // maintain every 7 cycles
  {"Rocker", 9, false},   // maintain every 10 cycles
  {"Shell Plate",  7, false},    // maintain every 3 cycles
  {"Zerks",  10, false},     // maintain every 2 cycles
  {"Cylinder",  13, false},     // maintain every 2 cycles
};

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

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

Toggle cycleButton;
Toggle maintenanceDoneButton;
Toggle encoderPB;
uint16_t _750ms = 750; // encoder button pressed for time delay

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


void saveState() {
  // eeprom stuff would go here
}

void restoreState() {
  // eeprom access stuff 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++;
      if (*txtBuffer != '\0') strlcat(txtBuffer, ", ", sizeof txtBuffer);
      strlcat(txtBuffer, p.label, sizeof txtBuffer);
    }
  }

  // erase
  for (byte r = 0; 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 line = 0;// start on line zero conserves display space
  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);
      }
    }
  }

  // disable display of parts needing maintenance and total number of parts
  // snprintf(txtBuffer, sizeof txtBuffer, "%03lu/%lu", partsNeedingMaintenanceCnt, lubePointsCnt);
  //  lcd.setCursor(0, 0);
  // lcd.print(txtBuffer);
}

void setup() {
  pinMode(alertPin, OUTPUT);
  cycleButton.begin(cyclePin);
  theEncoder.begin();
  encoderPB.begin(encoderSW);
  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();
  lcd.print("Total Cycles");
  showCycles();
  delay(2000);
  showMaintenanceList();
  delay(1000);
  Serial.println("started");
}
//==========================================================
void loop() {

  static bool encoderPBOS;
  static bool encoderPBOSSetup;
  static bool editMode;
  static int encoderValue=0;
  uint8_t x= theEncoder.read();
  uint16_t step;

 // maintenanceDoneButton.poll();
  encoderPB.poll();

  encoderPBOS = (encoderPB.pressedFor(750) and encoderPBOSSetup);
  encoderPBOSSetup = (! encoderPB.pressedFor(750)) ;
  if (encoderPBOS)editMode = true;

  //Serial.println(encoderPB.pressedFor(_750ms));

  if (!editMode) { // do monitoring/alarming stuff
    cycleButton.poll();
    if (cycleButton.onPress()) {
      cycleCounter++;
      if (cycleCounter % 10 == 0) {
        saveState();
        Serial.println("eeprom save"); // eventually print to lcd
        delay(1500);
      }
      //showCycles(); disabled
      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();
  }
  else { // do preset changing stuff
    Serial.println("edit mode");
    delay(2000);
        uint8_t encRead = theEncoder.read();
    uint8_t encSpeed = theEncoder.speed();
    uint16_t encStep;
   // Serial.println("exiting edit mode");
    //delay(1500);
    encoderPB.poll();
    if(encoderPB.isPressed())
    editMode = false;
  }
} // end of loop