#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <serialStr.h>
#include <timeObj.h>
#include <resizeBuff.h>


class flowLC :  public LiquidCrystal_I2C,
                public idler {

  public:
          flowLC(int inCols,int inRows,float autoBlankMs=0);
  virtual ~flowLC(void);

  virtual void  begin();
  virtual void  showText(const char* outStr);
  virtual void  idle(void);

          int     cols;
          int     rows;
          bool    autoBlanking;
          float   autoBlankMs;
          timeObj blankingTimer;
};


flowLC::flowLC(int inCols,int inRows,float autoBlankMs=0)
  : LiquidCrystal_I2C(0x27,inCols,inRows),
  idler() {

  cols          = inCols;
  rows          = inRows;
  autoBlanking  = false;
  if (autoBlankMs>0) {
    blankingTimer.setTime(autoBlankMs);
    autoBlanking = true;
  }
}


flowLC::~flowLC(void) {  }


void flowLC::flowLC::begin() {

  LiquidCrystal_I2C::begin(cols,rows);
  if (autoBlanking) hookup();
  backlight();
}


void flowLC::showText(const char* outStr) {

  int numChars;
  int col;
  int row;

  clear();
  setCursor(0,0);
  numChars = min(strlen(outStr),cols*rows);
  col = 0;
  row = 0;
  if (autoBlanking) blankingTimer.start();
  for (int i=0;i<numChars;i++) {            // For each char of our string..
    if (col == cols || outStr[i]=='\n') {
      if (row<rows-1) {
        row++;
        col = 0;
        setCursor(col,row);
        if (outStr[i]=='\n') i++;
      } else {
        return;
      }
    }
    print(outStr[i]);
  }
}

void flowLC::idle(void) {

  if (blankingTimer.ding()) {
    clear();
    blankingTimer.reset();
  }
}


flowLC      ourDisplay(16,2,5000);
serialStr   strReader(&Serial,'\r');

void setup() {
  
  Serial.begin(9600);
  Serial.println("Type strings to display. Use black slash for line break.");
  strReader.setCallback(showText);
  ourDisplay.begin();
}

void showText(const char* outStr) {
  int   i;
  char* localCopy;

  i = 0;
  localCopy = NULL;
  if (outStr) {
    if (resizeBuff(strlen(outStr)+1,&localCopy)) {
      strcpy(localCopy,outStr);
      while(localCopy[i]) {
        if (localCopy[i]=='\\') {
          localCopy[i]='\n';
        }
        i++;
      }
      ourDisplay.showText(localCopy);
      resizeBuff(0,&localCopy);
    }
  }
}



void loop() { idle(); }