import CesiumUtil from './cesiumUtil'

const Cesium = (<any>window).Cesium
export default class HandleManage {
    handleType = {
        'rclick': Cesium.ScreenSpaceEventType.RIGHT_CLICK,
        'lclick': Cesium.ScreenSpaceEventType.LEFT_CLICK,
        'move': Cesium.ScreenSpaceEventType.MOUSE_MOVE,
        'ldown': Cesium.ScreenSpaceEventType.LEFT_DOWN,
        'lup': Cesium.ScreenSpaceEventType.LEFT_UP,
        'rdown': Cesium.ScreenSpaceEventType.RIGHT_DOWN,
        'rup': Cesium.ScreenSpaceEventType.RIGHT_UP
    }
    handlerBox = []
    viewer = null
    constructor (viewer) {
        this.viewer = viewer
    }
    create (type, callback) {
        let handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
        handler.setInputAction(evt => {
            let pos = evt.position
            let movePos = evt.endPosition 
            if (pos) {
                // 转化为笛卡尔坐标系
                let car3 = new CesiumUtil(this.viewer).xy2Car3(pos)
                // 是否有实体点中
                let pick = this.viewer.scene.pick(pos)
                // 点中的位置，场景中
                let position = this.viewer.scene.pickPosition(pos)
                // 球面点
                let rayPoint = this.viewer.scene.globe.pick(this.viewer.scene.camera.getPickRay(pos), this.viewer.scene);
                callback && callback({ car3, position, pick, rayPoint })
            } else if (movePos) {
                callback(evt)
            } else {
                callback && callback()
            }
        }, this.handleType[type])
        this.handlerBox.push(handler)
        return this.handlerBox.length - 1
    }
    // 移除事件
    remove (index) {
        this.handlerBox[index] && this.handlerBox[index].destroy()
    }
    
    // 移除所有绑定的事件
    removeAll () {
        this.handlerBox.forEach(handler => { handler.destroy() })
    }
}