import React from 'react'
import { Color } from "csstype"
import * as Cesium from 'cesium'
import createMVTWithStyle from './mvt'
import style from './style.module.css'

declare global {
  interface Window { CESIUM_BASE_URL: any; ol: any }
}

window.CESIUM_BASE_URL = './'

const ol = window.ol

export interface LayerStyle {
  lineColor: Color,
  lineWidth: number,
  fillColor: Color
}

interface Props extends LayerStyle {
  url: string,
  lng: number,
  lat: number,
  height: number,
  show: boolean
}

interface State {
  viewer: any
}

function createStyle (style: LayerStyle) {
  return new ol.style.Style({
    fill: new ol.style.Fill({
      color: style.fillColor,
      // stroke:"green"
    }),
    stroke: new ol.style.Stroke({
      color: style.lineColor,
      width: style.lineWidth,
      lineCap: "round",
    }),
  });
}

class VectorView extends React.Component<Props, State> {
  clipLayer: any

  constructor(props: Props) {
    super(props)
    this.state = { viewer: null }
  }

  componentDidUpdate () {
    if (!this.state.viewer) return;
    if (this.clipLayer) {
      this.state.viewer.imageryLayers.remove(this.clipLayer, true)
    }
    if (!this.props.show) return;

    let layer = createMVTWithStyle(Cesium, ol, {
      url: this.props.url,
      style: createStyle(this.props)
    }) as any;

    this.clipLayer = this.state.viewer.imageryLayers.addImageryProvider(layer);
  }

  componentDidMount () {
    let viewer = new Cesium.Viewer('cesiumContainer', {
      baseLayerPicker: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      timeline: false,
      animation: false,
      navigationHelpButton: false,
    });
    viewer.camera.flyTo({
      duration: 1,
      destination: Cesium.Cartesian3.fromDegrees(this.props.lng, this.props.lat, this.props.height)
    });
    viewer.scene.globe.baseColor = new Cesium.Color(1.0, 1.0, 1.0, 1.0);
    this.setState({ viewer })
  }

  componentWillUnmount() {
    if (this.state.viewer) {
      this.clipLayer && this.state.viewer.imageryLayers.remove(this.clipLayer, true)
      this.state.viewer.destroy()
    }
  }

  render() {
    return <div id="cesiumContainer" className={style.layer}></div>
  }
}

export default VectorView