const { Gpio } = require('onoff');
const hotwater = require('./modules/water')
const common = require('./libs/common')
const globalVars = require('./libs/globalVars')
const led = require('./libs/led')
const lcd = require('./libs/lcd')
const menu = require('./modules/mainMenu')

async function main() {
  lcd.clearScreen()
  await lcd.intro()
  menu.home()

  const heatingSwitch = new Gpio('17', 'in', 'both');
  const appSwitch = new Gpio('23', 'in', 'both');

  heatingSwitch.watch(async (err, value) => {
    if (err) {
      console.log('Error', err);
    }
    if (value === 1) {
      if (globalVars.waterOn === 'true') {
        common.request(0)
      } else {
        common.request(1)
      }
    }
  })

  const arr = ['water', 'heating', 'mainMenu']
  arrLength = arr.length
  let i = 0
  appSwitch.watch(async (err, value) => {
    if (err) {
      console.log('Error', err);
    }
    if (value === 1) {
      switch (arr[i]) {
        case 'water':
          await menu.water()
          break;
        case 'mainMenu':
          clearInterval(globalVars.heatingPolling)
          led.set('off')
          await menu.home()
          break;
        case 'heating':
          clearInterval(globalVars.waterPolling)
          led.set('off')
          await menu.heating()
          break;
        default:
          break;
      }
      console.log(arr[i])
      i = i + 1
      if (i === arrLength) {
        i = 0
      }
    }
  })
}

process.stdin.resume();

process.on('SIGINT', function () {
  lcd.clearScreen()
  led.set('off')
  process.exit(1)
});

main()