import bindEvents from '../Base/Cesium/CesiumBindEvent'
import { Events } from '../Base/Cesium/CesiumEvents'
import cmp from '../Base/Vue/VueVirtualCmp'
import { show } from '../Base/Cesium/CesiumMixinProps'
import mergeDescriptors from '../Utils/mergeDescriptors'

const methods = {
  async mount () {
    const { dataSources, datasource } = this
    bindEvents.call(this, datasource, Events['datasource-events'], true)
    Events['datasource-property-events'].forEach((eventName) => {
      datasource[eventName.name] && bindEvents.call(this, datasource[eventName.name], eventName.events, true)
    })
    datasource.show = this.show
    return dataSources && dataSources.add(datasource)
  },
  async unmount () {
    const { dataSources, datasource } = this
    bindEvents.call(this, datasource, Events['datasource-events'], false)
    Events['datasource-property-events'].forEach((eventName) => {
      datasource[eventName.name] && bindEvents.call(this, datasource[eventName.name], eventName.events, false)
    })
    return dataSources && dataSources.remove(datasource)
  },
  getServices () {
    const vm = this
    return mergeDescriptors(cmp.methods.getServices.call(this), {
      get datasource () {
        return vm.datasource
      },
      get entities () {
        return vm.datasource.entities
      }
    })
  }
}
export default {
  mixins: [cmp, show],
  methods,
  stubVNode: {
    attrs () {
      return {
        class: this.$options.name
      }
    }
  },
  created () {
    Object.defineProperties(this, {
      datasource: {
        enumerable: true,
        get: () => this.cesiumObject
      },
      dataSources: {
        enumerable: true,
        get: () => this.$services && this.$services.dataSources
      }
    })
  }
}
