import { world, ItemStack } from '@minecraft/server'
import { ActionFormData, MessageFormData } from '@minecraft/server-ui'

export default class guideBook {
  constructor (guideBookData) {
    this.guideBookData = guideBookData
    this.guideBook = {
      id: 'sqst_mnts:guide',
      lore: 'By Scai Quest',
      sound: 'item.book.page_turn'
    }
    this.guideForms = [] // { form: tempForm, links: tempLinkMap }
    this.createForm()

    world.afterEvents.playerSpawn.subscribe(eventData => {
      let { player: eventPlayer, initialSpawn } = eventData
      // when the player joins the world
      if (initialSpawn) {
        let tempDynProps = eventPlayer.getDynamicPropertyIds()
        // console.warn(JSON.stringify(tempDynProps))
        if (!tempDynProps.includes('sqst_mnts_guide')) {
          const playerPosition = eventPlayer.location
          const tempItemStack = new ItemStack(this.guideBook.id, 1)
          tempItemStack.setLore([this.guideBook.lore])
          eventPlayer.dimension.spawnItem(tempItemStack, playerPosition)
          eventPlayer.setDynamicProperty('sqst_mnts_guide', 1)
          eventPlayer.sendMessage({ translate: 'sqst_mnts.chat.intro', with: ['\n'] })
        }
      }
    })

    world.afterEvents.itemUse.subscribe(eventData => {
      let { source: eventPlayer, itemStack: eventItem } = eventData
      if (
        eventPlayer.typeId === 'minecraft:player' &&
        eventItem.typeId === this.guideBook.id
      ) {
        this.showForm(eventPlayer,0)
      }
      // debugging
      // else if (eventItem.typeId === 'minecraft:compass') {
      //   eventPlayer.clearDynamicProperties()
      //   let tempDynProps = world.getDynamicPropertyIds()
      //   console.warn(JSON.stringify(tempDynProps))
      // }
    })
  }

  showForm(inputPlayer, inputIndex){
    inputPlayer.playSound(this.guideBook.sound)
    // display form
    this.guideForms[inputIndex].form.show(inputPlayer).then(formResponse => {
      if (formResponse.canceled) {
        // console.warn("Canceled")
        inputPlayer.playSound(this.guideBook.sound)
        return
      }
      // console.warn(`Selection: ${formResponse.selection} || Target: ${this.guideForms[inputIndex].links[formResponse.selection].target}`)
      if(this.guideForms[inputIndex].links[formResponse.selection].target ===-1 ){
        // console.warn("Close Guide")
        inputPlayer.playSound(this.guideBook.sound)
        return
      }
      this.showForm(inputPlayer,this.guideForms[inputIndex].links[formResponse.selection].target)
      return
    })
  }

  createForm () {
    this.guideBookData.forEach(eachForm => {
      // ==================== ActionFormData =========================
      if (eachForm.formType === 0) {
        let tempForm = new ActionFormData()
        // get the number of paragraphs
        let tempBodyLen = eachForm.text.length

        // construct the body of the form
        let tempBody = { rawtext: [] }
        for (let i = 0; i < tempBodyLen; i++) {
          // if (i == 0) {
          //   tempBody.rawtext.push({ text: '§r\n' })
          // }
          tempBody.rawtext.push({translate: eachForm.text[i],with: ['\n']})
          tempBody.rawtext.push({ text: '§r\n\n' })
        }

        // build the form
        tempForm.title({ translate: eachForm.formTitle, with: ['\n'] })
        tempForm.body(tempBody)

        // build button list from links
        let tempLinkMap = []
        let tempLinkIndex = -1
        eachForm.links.forEach(eachLink => {
          tempLinkIndex += 1
          tempLinkMap.push({
            selection: tempLinkIndex,
            target: eachLink
          })

          tempForm.button(
            { translate: this.guideBookData[eachLink].formTitle, with: ['\n'] },
            this.guideBookData[eachLink].buttonImage
          )
        })

        // close button
        tempForm.button({translate: eachForm.buttons.close,with: ['\n']})
        tempLinkMap.push({ selection: tempLinkIndex+1, target: -1 })

        // add form to list
        this.guideForms.push({ form: tempForm, links: tempLinkMap })
      }
      // ==================== MessageFormData =========================
      else if (eachForm.formType === 1) {
        let tempForm = new MessageFormData()

        // get the number of paragraphs
        let tempBodyLen = eachForm.text.length

        // construct the body of the form
        let tempBody = { rawtext: [] }
        for (let i = 0; i < tempBodyLen; i++) {
          // if (i == 0) {
          //   tempBody.rawtext.push({ text: '§r\n' })
          // }
          tempBody.rawtext.push({ translate: eachForm.text[i], with: ['\n'] })
          tempBody.rawtext.push({ text: '§r\n\n' })
        }

        // build the form
        tempForm.title({ translate: eachForm.formTitle, with: ['\n'] })
        tempForm.body(tempBody)

        // build button list from links
        let tempLinkMap = [
          { selection: 0, target: -1 },
          { selection: 1, target: eachForm.links[0] }
        ]

        // back button
        tempForm.button2({ translate: eachForm.buttons.back, with: ['\n'] })
        // close button
        tempForm.button1({translate: eachForm.buttons.close,with: ['\n']})

        // add form to list
        this.guideForms.push({ form: tempForm, links: tempLinkMap })
      }
    })
  }
}
