<template>
  <div>
    <div v-if="(statics('pokemon').v === undefined) || (statics('pokemon').v.abilities === undefined) || (statics('pokemon').v.abilities[0].ability.name === undefined)">Loading...</div>
    <div v-else class="poke-abilities">
      <button type="button" class="btn btn-primary" @click="clickHandler(0)">{{statics('pokemon').v.abilities ? statics('pokemon').v.abilities[0].ability.name : ''}}</button>
      <button type="button" class="btn btn-secondary" @click="clickHandler(1)" v-if="statics('pokemon').v.abilities && statics('pokemon').v.abilities[1]">{{statics('pokemon').v.abilities[1].ability.name}}</button>
    </div>
    <modal-core :show="currentAbility" @close="currentAbility = undefined">{{value.name | capitalize}} used {{currentAbility2}}<br/>It was {{effectiveness}} effective.</modal-core>
  </div>
</template>

<script lang="babel">
  import ModalCore from './ModalCore'
  let loseCode = str => {
    var hash = 0
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i)
      hash += char
    }
    return hash
  }
  export default {
    data () {
      return {
        currentAbility: undefined,
        lastAbility: undefined,
        lastEffectiveness: undefined
      }
    },
    methods: {
      clickHandler (index) {
        this.currentAbility = this.statics('pokemon').v.abilities[index].ability.name
      }
    },
    computed: {
      currentAbility2 () {
        if (this.currentAbility !== undefined) {
          this.lastAbility = this.currentAbility
        }
        return this.lastAbility
      },
      effectiveness () {
        let dice
        if (this.currentAbility === undefined) {
          dice = this.lastEffectiveness
        } else {
          dice = Math.round(loseCode(String(this.id)) +
            loseCode(String(this.currentAbility ? this.currentAbility : ''))) % 4
          this.lastEffectiveness = dice
        }
        switch (dice) {
          case 0:
            return 'super'
          case 1:
            return 'normal'
          case 2:
            return 'not very'
          case 3:
            return 'not'
        }
      }
    },
    ready () {
      if (this.statics('pokemon').v === undefined) {
        this.statics('pokemon').v = 'loading'
        this.$http.get('https://pokeapi.co/api/v2/pokemon/' + this.value.name).then(response => {
          console.log('response for ability')
          const json = response.json()
          this.statics('pokemon').v = json
        }, response => {
          console.error(response)
        })
      }
    },
    components: { ModalCore }
  }
</script>

<style>
  .poke-abilities {
    display: flex;
    flex-direction: column;
    width: 165px;
  }
  
  button {
    margin: 3px 2px;
  }
</style>