import Layer from '../layer'
import { LineLayer, Popup } from '@cgcs2000/l7'
import renderPopup from '../libs/render_popup'

class Line extends Layer {
  constructor(layer, scene, zIndex) {
    super(layer, scene, zIndex)
    let { visible, minZoom, maxZoom } = this.layer
    this.layerInstance = new LineLayer({
      visible: visible === undefined ? true : !!visible,
      minZoom: Number(minZoom) || 0,
      maxZoom: Number(maxZoom) || 18,
      zIndex
    })
    this.setSource()
    this.layerInstance.on('click', e => {
      const popup = new Popup({
        offsets: [0, 0],
        closeButton: true
      })
        .setLnglat(e.lngLat)
        .setHTML(renderPopup(e.feature))
      scene.addPopup(popup)
    })
  }

  setShape() {
    let { shape } = this._mergeProperties()
    this.layerInstance.shape(shape)
  }

  setStyle() {
    let { style } = this._mergeProperties()
    let { lineWidth, color, animate } = style
    this.layerInstance.size(lineWidth)
    if (typeof color === 'string') {
      this.layerInstance.color(color)
    } else {
      let { field, type, stops } = color
      if (type === 'interval') {
        this.layerInstance.color(field, value => {
          let st = stops.find(stop => {
            let { min, max } = stop
            min = typeof min !== 'number' ? -Infinity : min
            max = typeof max !== 'number' ? Infinity : max
            return value >= min && value <= max
          })
          if (st) {
            return st.color
          } else {
            return '#000000'
          }
        })
      } else {
        this.layerInstance.color(field, value => {
          let st = stops.find(stop => stop.value == value)
          if (st) {
            return st.color
          } else {
            return '#000000'
          }
        })
      }
    }
    this.layerInstance.style({
      lineType: style.lineType,
      dashArray: style.dashArray
    })
    this.layerInstance.animate(animate || false)
  }
}

export default Line
