const { addAchievement, saveGame, getUser, saveUser } = require('./utils')
const slack = require('../../slack')

let loreCount = 0
const l = (text, {file, correctReactions, correctResponse, incorrectResponse, jumpTo} = {}) => {
  loreCount += 1
  return {
    text,
    file,
    correctReactions,
    correctResponse,
    incorrectResponse,
    jumpTo
  }
}

const lore = [
  l(`Allow me to tell you a story.`),
  l(`Once upon a time, there were two young ducks named Genevieve and Isaiah.`),
  l(`Isaiah was known mostly for being a big butthole whomst no one liked.`),
  l(`Genevieve was known for a singing voice that could peel the paint off your car.`),
  l(`Nevertheless, there's was a passionate love affair.`),
  l(`_Honking_`),
  l(`...`),
  l(`Hey you know, it's rather cold, don't you think? Could you start a fire for us?`, {
    correctReactions: ['fire'],
    correctResponse: `Thank you.`,
    incorrectResponse: `Well, you're looking in the right place, anyway.`,
  }),

  l(`Anyway, together they laid nine eggs.`),
  l(`The first to hatch was Rick, who grew up into a fine bird with beautiful feathers.`),
  l(`The second was Claire, who grew into an even finer bird, glowing with Duckish beauty.`),
  l(`The third was Marf, who developed a severe addiction to Elmer's glue.`),
  l(`Bird four was Yoink, who considered Tupperware a hobby.`),
  l(`The fifth was Big Bob.`),
  l(`The sixth was Jess, who became the number one checkers player in the world.`),
  l(`The seventh was Small Bob.`),
  l(`The eighth was Maurice, who had quite a few words to say about the French, and was eventually elected president.`),
  l(`And the ninth...`),
  l(`Well, the ninth might actually amount to something.`, {file: 'https://i.imgur.com/eFreg7Y.gif'})
]

slack.onReaction(async ({ event, say }) => {
  try {
    const user = await getUser(event.user)
    const item = await slack.getMessage({ channel: event.item.channel, ts: event.item.ts })
    const message = item.messages[0].text
    const loreData = slack.decodeData('lore', message)
    if (!loreData || user.lore !== loreData.index || !loreData.correctReactions) {
      return
    }
    if (!loreData.correctReactions.includes(event.reaction)) {
      if (lore[user.lore].incorrectResponse) {
        await say(lore[user.lore].incorrectResponse + encodeLore(user.lore))
      }
      return
    }
    console.log('lore:', lore[user.lore])
    await say(lore[user.lore].correctResponse)
    user.lore += 1
    saveUser(event.user, user, 'updating lore counter')
  } catch (e) {console.error('onReaction error', e)}
})

const encodeLore = loreNumber => lore[loreNumber].text.startsWith(':') && lore[loreNumber].text.endsWith(':') ? '' :
  slack.encodeData('lore', {
    index: loreNumber,
    correctReactions: lore[loreNumber].correctReactions
  })

const loreMessage = (user, say) => {
  if (lore[user.lore]) {
    return lore[user.lore].text + encodeLore(user.lore)
  }
  addAchievement(user, 'bookWorm', say)
  return `Sorry. I'd love to tell you more, but I'm tired. Please check back later.`
}

const loreRoute = async ({ say, args, user, isAdmin, event }) => {
  user.lore ??= 0
  if (!args[0]) {
    const message = loreMessage(user, say)
    await say(message)
    if (!lore[user.lore]?.correctReactions) {
      user.lore += 1
    }
    //saveGame()
    console.log('Sent ' + user.name + ':\n' + message)
    return
  }
  if (args[0] === 'reset') {
    user.lore = 0
    //saveGame()
    await saveUser(event.user, user, 'lore reset')
    return say(`I have reset your place in the story.`)
  }
  if (isAdmin) {
    if (args[0] === 'all') {
      let loreMessage = ''
      for (let i = 0; i < user.lore; i++) {
        loreMessage += lore[i].text + (lore[i].correctResponse || '') + '\n'
      }
      return say(loreMessage)
    }
    const jumpTo = parseInt(args[0])
    if (!isNaN(jumpTo)) {
      user.lore = jumpTo
      await saveUser(event.user, user, 'lore jump')
      //saveGame()
    }
  }
}

module.exports = loreRoute
