import {
  getCesiumLayerIndex,
  getTilingSchemeBySpatialReference
} from './support/utils'

class WMSLayerUtil {}

/**
 * 添加WMS图层
 * @param {WMSLayer} layer WMS图层基本对象
 * @param {Viewer} innerView Cesium的视图对象
 * @return {Object} 创建的WMS图层对象
 * */
WMSLayerUtil.addWMSLayer = function (layer, innerView) {
  const tilingScheme = getTilingSchemeBySpatialReference(
    layer.spatialReference,
    layer.extent
  )

  const options = {
    url: layer.url,
    layers: layer.layers,
    parameters: {
      format: layer.imageFormat,
      transparent: layer.imageTransparency
    },
    // 裁图方式
    tilingScheme,
    // 瓦片宽度
    tileWidth: layer.imageWidth,
    // 瓦片高度
    tileHeight: layer.imageHeight,
    // 在WebMapServiceImageryProvider中会根据WMS版本和投影类型判断crs或srs
    // 原生实现只支持EPSG:3857和EPSG:4326，自定义投影坐标系需要显式指定crs或srs
    srs: `EPSG:${layer.spatialReference.wkid}`
  }
  // 获取图层index
  const index = getCesiumLayerIndex(layer, innerView)
  // 加载WMS地图
  const wmsLayer = innerView.scene.imageryLayers.addImageryProvider(
    new Cesium.WebMapServiceImageryProvider(options),
    index
  )

  wmsLayer.id = layer.id
  wmsLayer._realIndex = layer._realIndex + 1
  return wmsLayer
}

/**
 * 移除图层
 * @param {Object} layer 图层对象
 * @param {Viewer} innerView Cesium的视图对象
 * */
WMSLayerUtil.removeLayer = function (layer, innerView) {
  innerView.scene.imageryLayers.remove(layer)
}

export default WMSLayerUtil
