<template>
  <div class="">
    <div class="spinner" v-show="loading">
      <div class="pokeball">
        <div class="pokeball__button"></div>
      </div>
    </div>
    <img :src="source" v-else></img>
  </div>
</template>

<script lang="babel">
  import Vue from 'vue'
  function getDataFromDotNotation (d, obj) {
    return d.split('.').reduce((o, i) => { if (o === undefined) { return undefined } else { return o[i] } }, obj)
  }
  export default {
    data () {
      return {
        loading: true,
        source: undefined
      }
    },
    props: ['urlPath'],
    ready () {
      this.$http.get(this.value).then(response => {
        // The component could be already destroyed then this is fired
        if (this._isDestroyed) {
          return
        }
        Vue.set(this, 'source', getDataFromDotNotation(this.urlPath, response.data))
        this.$el.querySelector('img').addEventListener('load', () => Vue.set(this, 'loading', false))
      }, response => {
        console.error('something gone wrong with the pokemon api')
      })
      /*
      use to simulate response when server is busy
      setTimeout(() => {
        Vue.set(this, 'source', 'http://pokeapi.co/media/sprites/pokemon/' + this.value.match(/pokemon.+([1-9])/)[1] + '.png')
        Vue.set(this, 'loading', false)
      }, 300 + Math.random() * 100)*/
    }
  }
</script>

<style>
.spinner {
  position: relative;
  left: 21px;
  top: 38px;
}

 /* Poké Styles */
.pokeball {
  position: relative;
  width: 50px;
  height: 50px;
  background: #fff;
  border: 3px solid #000;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: inset -10px 10px 0 10px #ccc;
  animation: fall .25s ease-in-out,
             shake 1.25s cubic-bezier(.36,.07,.19,.97) infinite;
}
.pokeball::before,
.pokeball::after {
  content:"";
  position: absolute;
}
.pokeball::before {
  background: red;
  width: 100%;
  height: 50%;
}
.pokeball::after {
  top: calc(50% - 2.5px);
  width: 100%;
  height: 5px;
  background: #000;
}
.pokeball__button {
  position: absolute;
  top: calc(50% - 7.5px);
  left: calc(50% - 7.5px);
  width: 15px;
  height: 15px;
  background: #7f8c8d;
  border: 3px solid #fff;
  border-radius: 50%;
  z-index: 10;
  box-shadow: 0 0 0 3px black;
  animation: blink .5s alternate infinite;
}
/* Animation */
@keyframes blink {
  from { background: #eee;}
  to { background: #e74c3c; }
}
@keyframes shake {
  0 { transform: translate(0, 0) rotate(0); }
  20% { transform: translate(-10px, 0) rotate(-20deg); }
  30% { transform: translate(10px, 0) rotate(20deg); }
  50% { transform: translate(-10px, 0) rotate(-10deg); }
  60% { transform: translate(10px, 0) rotate(10deg); }
  100% { transform: translate(0, 0) rotate(0); }
}
@keyframes fall {
  0% { top: -200px }
  60% { top: 0 }
  80% { top: -20px }
  100% { top: 0 }
}
</style>