<template src="./Gmap.html"></template>

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

export default {
  mixins: [GmapMixin],
  props: {
    data: { type: Object },
    editable: { type: Boolean, default: true },
    styler: { tyoe: Function }
  },
  watch: {
    data: {
      deep: true,
      handler () {
        this.drawData()
      }
    },
    editable () {
      if (!this.map || !this.map.data) return
      this.map.data.setStyle({ editable: this.editable })
    }
  },
  async mounted () {
    await this.$initializeMap()
    this.drawData()
  },
  methods: {
    getGeojson () {
      return this.map.getGeoJson()
    },
    drawData () {
      this.map.data.forEach((data) => this.map.data.remove(data))
      if (!this.data) return
      this.map.data.addGeoJson(this.data)
      this.map.data.setStyle({ editable: this.editable })
      if (this.styler) {
        this.map.data.setStyle(this.styler)
      }
      this.autocenter()
      // const bounds = this.map.getBounds()
      // console.log('bounds', bounds)
      // if (!bounds) return
      // this.map.fitBounds(bounds)
      // setTimeout(() => {
      //   const bounds = this.map.getBounds()
      //   this.map.fitBounds(bounds)
      // })
    },
    autocenter () {
      console.log('this.data.type', this.data)
      var bounds = new window.google.maps.LatLngBounds()
      if (this.data.type === 'Feature') {
        this.data.geometry.coordinates.forEach((coords) => {
          bounds.extend(new window.google.maps.LatLng(coords[1], coords[0]))
        })
      } else if (this.data.type === 'FeatureCollection') {

      }
      this.map.fitBounds(bounds)
      // console.log(this.map)
      // const bounds = this.map.getBounds()
      // if (bounds) {
      //   alert('bounds:\n'+bounds.toString());
      // }
    }
  }
}
</script>
