import {
  LayerView,
  Projection,
  SpatialReference
} from '@mapgis/webclient-common'
import { VectorTileLayer } from '../plugin'
import { getTilingSchemeBySpatialReference } from '../view/utils/support/utils'

class IGSVectorTileLayerView extends LayerView {
  /**
   * 添加图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onAdd(event) {
    const layer = this.layer
    const innerView = this.innerView
    const self = this

    const tilingScheme = getTilingSchemeBySpatialReference(
      layer.spatialReference,
      layer.extent,
      layer.tileInfo
    )

    let extent
    if (layer.extent) {
      extent = Projection.project(
        layer.extent,
        new SpatialReference('EPSG:4326')
      )
    }

    return new Promise((reslove) => {
      // 设置labelNoteStyle
      const labelsNoteStyle =
        Array.isArray(layer.labelingInfo) && layer.labelingInfo.length > 0
          ? layer.labelingInfo[0]
          : undefined
      // 必须设置innerLayer
      self.innerLayer = new VectorTileLayer(innerView, {
        tilingScheme,
        wgs84Extent: extent,
        labelsRenderMode: layer.labelsRenderMode,
        labelsNoteStyle,
        style: layer.style,
        addCallback() {
          // 请求成功信息
          reslove(self)
        }
      })
      self.innerLayer.id = layer.id
    })
  }

  /**
   * 移除图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onRemove(event) {
    this.innerLayer.remove()
    return Promise.resolve(this)
  }

  /**
   * 更新图层视图
   * @param {LayerViewUpdateEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onUpdate(event) {
    const _layer = this.innerLayer
    _layer.updateStyle(this.layer.style)
    // 更新样式
    return Promise.resolve(this)
  }
}
export default IGSVectorTileLayerView
