import { LayerView } from '@mapgis/webclient-common'
import { getLayerIndex, updateLayerIndex } from './support/Utils'
import ArcGISTileLayerUtil from '../view/utils/ArcGISTileLayerUtil'

class ArcGISTileLayerView extends LayerView {
  /**
   * 添加图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onAdd(event) {
    const layer = this.layer
    const innerView = this.innerView
    // 获取map里的所有图层
    const items = this.view._map.layers.items
    // 获取当前图层的上一个图层的index
    const index = getLayerIndex(items, layer)
    const self = this
    return new Promise((resolve) => {
      // 确保上一个图层的资源加载完毕
      const interval = setInterval(function () {
        if (items[index].loadStatus === 'loaded') {
          self.innerLayer = ArcGISTileLayerUtil.addArcGISTileLayer(
            layer,
            innerView
          )
          clearInterval(interval)
          resolve(self)
        }
      }, 1)
    })
  }

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

  /**
   * 更新图层视图
   * @param {LayerViewUpdateEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onUpdate(event) {
    // 确保有updateContent
    if (event.updateContent) {
      for (let i = 0; i < event.updateContent.length; i++) {
        const updateContent = event.updateContent[i]
        // 有updateContent
        if (updateContent) {
          switch (updateContent.name) {
            // 更新主图层可见性
            case 'visible':
              this.innerLayer.show = !this.innerLayer.show
              break
            // 更新透明度
            case 'opacity':
              this.innerLayer.alpha = this.layer.opacity
              break
            // 更新图层顺序
            case 'index':
              updateLayerIndex(this.layer, this.innerLayer, this.innerView)
              break
            default:
              break
          }
        }
      }
    }
    return Promise.resolve(this)
  }
}
export default ArcGISTileLayerView
