<template>
<div>
  <img :src="gUrl" />
</div>
</template>

<script>
import Vue from 'vue'
import GmapMixin from '../mixins/GmapMixin'

const staticMapBaseUrl = 'https://maps.googleapis.com/maps/api/staticmap'

let resizeComponents = []
const optionsToUrl = (options = {}) => {
  return Object.keys(options).map((opt) => `${opt}=${options[opt]}`).join('&')
}
const registerComponent = (vm) => {
  resizeComponents.push(vm)
  setTimeout(() => vm.updateGurl(vm.$el.offsetWidth))
}
setInterval(() => {
  let newWidth
  resizeComponents.forEach((instance) => {
    newWidth = instance.$el.offsetWidth
    if (instance.resizeWidth !== newWidth) {
      instance.updateGurl(newWidth)
      instance.resizeWidth = newWidth
    }
  })
}, 500)


export default {
  mixins: [GmapMixin],
  props: {
    url: {type: String},
    width: {type: Number},
    height: {type: Number, default: 200},
    options: {type: Object}
  },
  data () {
    return {
      resizeWidth: 0,
      responsive: false,
      gUrl: ''
    }
  },
  created () {
    if (!this.width) {
      this.responsive = true
    }
  },
  async mounted () {
    await Vue.$bvueGmapWaitGoogleReady()
    if (this.responsive) registerComponent(this)
    else this.updateGurl(this.width)
  },
  methods: {
    updateGurl (newWidth) {
      const width = newWidth || this.width
      if (!width) return
      this.gUrl = `${staticMapBaseUrl}?${optionsToUrl({
        ...(this.options || {}),
        key: Vue.$bvueGmapKey,
        size: `${width}x${this.height}`,
        zoom: this.zoom,
        center: this.$resolveCenter().reverse().join(',')
      })}`
    }
  },
  destroyed () {
    resizeComponents.splice(resizeComponents.indexOf(this), 1)
  }
}
</script>
