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

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

export default {
  model: {
    prop: 'model',
    event: 'input'
  },
  mixins: [GmapMixin],
  props: {
    model: {type: Array},
    icon: {type: String},
    editable: { type: Boolean, default: false }
  },
  watch: {
    editable () {
      if (!this.marker) return
      this.marker.setDraggable(this.editable)
    },
    model () {
      this.marker.setPosition(new window.google.maps.LatLng(this.model[1], this.model[0]))
    }
  },
  async mounted () {
    await this.$initializeMap()
    this.drawMarker()
  },
  methods: {
    clearMarker () {
      if (this.marker) this.marker.setMap(null)
      this.marker = null
    },
    drawMarker () {
      this.marker = new window.google.maps.Marker({
        icon: this.icon && {
          url: this.icon,
          scaledSize: new window.google.maps.Size(50, 50),
          anchor: new window.google.maps.Point(25, 60)
        },
        position: new window.google.maps.LatLng(this.model[1], this.model[0]),
        map: this.map,
        draggable: this.editable
      })
      this.marker.addListener('click', () => this.$emit('marker-click', this.marker))
      if (this.editable) window.google.maps.event.addListener(this.marker, 'dragend', this.modelChanged)
    },
    modelChanged () {
      this.$emit('input', [this.marker.position.lng(), this.marker.position.lat()])
    }
  }
}
</script>

