#include "state.h"
#include "epaperdisplay.h"

namespace {
  std::string lnurl_str = "";
  bool update_value = false;

  static atm::State current_state = atm::State::INIT;
  static atm::State next_state = atm::State::INIT;
}

namespace atm {
  void reset(void)
  {
    current_state = INIT;
    next_state = INIT;
  }

  void stateMachine(void)
  {
    switch (current_state) {
      case INIT:
          update_value = false;
          ok_button.ledOff();
          ok_button.reset();
          cancel_button.ledOff();
          cancel_button.reset();
          epDisp.homeScreen();
          cacc.resetSumValue();
          cacc.enable();
          next_state = WAIT_FOR_COIN;
          break;
      case WAIT_FOR_BUTTON:
          if(ok_button.wasPressed())
          {        
            next_state = GENERATE_QR;
            ok_button.reset();
          }
          if(cancel_button.wasPressed())
          {
            next_state = CANCEL_PAYMENT;
            cancel_button.reset();
          }          
      case WAIT_FOR_COIN:
          if(true == cacc.detectCoin())
          {
            next_state = PROCESS_COIN;
          }
          break;
      case PROCESS_COIN:
          Serial.printf("Summe: '%s' (cents %d) \n", cacc.getSumValueStr().c_str(), cacc.getSumValue());
          Serial.printf("%s\n", cacc.getCoinsNumStr().c_str());
          Serial.printf("%s\n", cacc.getCoinsValStr().c_str());
          epDisp.showInsertedAmount(cacc.getSumValueStr().c_str(),cacc.getCoinsValStr().c_str(), cacc.getCoinsNumStr().c_str(), "", update_value);
          update_value = true;          
          ok_button.ledOn();
          ok_button.reset();
          cancel_button.ledOn();
          ok_button.reset();
          cacc.enable();
          next_state = WAIT_FOR_BUTTON;          
          break;
      case GENERATE_QR:
          //lnurl_str = lnurlutil::createQrContent(0.05);
          epDisp.qrCode(lnurl_str.c_str());
          next_state = PAYMENT_CONFIRMED;
          ok_button.wasPressed();        
          break;
      case CANCEL_PAYMENT:
          break;
      case PAYMENT_CONFIRMED:
          if(ok_button.wasPressed())
          {
            next_state = INIT;
            ok_button.wasPressed();
          }
          break;

      case ERROR_STATE:
          next_state = WAIT_FOR_COIN;
          break;
    }

    current_state = next_state;

  }

}