<template>
  <div :style="{ height:`${opts.height}px`, width:`${opts.width}px` }" style="position:relative;">
    <div class="cont" ref='map'></div>
  </div>
</template>

<script>
import { createFromConfig, useTheme } from '@amcharts/amcharts4/core'
import { MapChart               }           from '@amcharts/amcharts4/maps'
import { MapBuilder             }           from '@modules/map-builder'
import   am4themes_animated                 from '@amcharts/amcharts4/themes/animated'// eslint-disable-line
import { geoDataPoliticalUpdate }           from '@modules/political-mapping'
import   worldGeoData                       from '@amcharts/amcharts4-geodata/worldLow'
import { DefaultOptions }                   from '@modules/default-options'


export default {
  name    : 'AmMap',
  props   : { options: { type: Object, required: true } },
  methods : { constructMap },
  computed: { opts },
  mounted,
  data,
  beforeDestroy,
  errorCaptured
}

function errorCaptured(err, vm){
  dispose(vm.$data.map)
  console.error(err)
}

function opts(){ return DefaultOptions.get(this.options || {}) }

function data(){
  const map  = {}

  return { map }
}

function beforeDestroy(){ dispose(this.map) }

function mounted (){
  useTheme(am4themes_animated) // eslint-disable-line

  setTimeout(this.constructMap, 50)
  // not sure why but map does not mount without a bit of a time out
}

function constructMap(){
  const geodata  = geoDataPoliticalUpdate(worldGeoData)
  const { main } = this.opts.config

  console.log(geodata)
  const map      = createFromConfig({ ...main, geodata }, this.$refs.map, MapChart)

  this.map = new MapBuilder(map, this.opts)
}

function dispose(map){ if(map && map.dispose) map.dispose() }


</script>

<style scoped>
  @import "https://fonts.googleapis.com/css?family=BenchNine:300,400,600,900";
  .cont{ width: 100%; height: 450px; }
</style>