#include "state.h"
#include "epaperdisplay.h"
#include "lnurlutil.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;
            cacc.disable();
            ok_button.reset();
          }
          if(cancel_button.wasPressed())
          {
            next_state = CANCEL_PAYMENT;
            cacc.disable();
            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(cacc.getSumValue()/100.0);
          epDisp.qrCode(lnurl_str.c_str(), cacc.getSumValueStr().c_str());
          next_state = PAYMENT_CONFIRMED;
          ok_button.reset();
          cancel_button.ledOff();        
          break;
      case CANCEL_PAYMENT:
          epDisp.cancelScreen();
          next_state = CANCEL_CONFIRMED;
          cancel_button.reset(); 
          ok_button.ledOff();              
          break;
      case PAYMENT_CONFIRMED:
          if(ok_button.wasPressed())
          {
            next_state = INIT;
            ok_button.reset();
          }
          break;
      case CANCEL_CONFIRMED:
          if(cancel_button.wasPressed())
          {
            next_state = INIT;
            cancel_button.reset();
          }
          break;
      case ERROR_STATE:
          next_state = WAIT_FOR_COIN;
          break;
    }

    current_state = next_state;

  }

}