var selector;
var firstPointSet = false;
var mouseDown = false;
var camera

export function drawRectangle(Cesium, viewer, screenSpaceEventHandler,cb) {
    if (camera) {
        return
    }

    var rectangleSelector = new Cesium.Rectangle();
    var screenSpaceEventHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    var cartesian = new Cesium.Cartesian3();
    var tempCartographic = new Cesium.Cartographic();
    var center = new Cesium.Cartographic();
    var firstPoint = new Cesium.Cartographic();

    camera = viewer.camera;

    screenSpaceEventHandler.setInputAction(function drawSelector(movement) {
        if (!mouseDown) {
            return;
        }

        cartesian = camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid, cartesian);

        if (cartesian) {
            //mouse cartographic
            tempCartographic = Cesium.Cartographic.fromCartesian(cartesian, Cesium.Ellipsoid.WGS84, tempCartographic);

            if (!firstPointSet) {
                Cesium.Cartographic.clone(tempCartographic, firstPoint);
                firstPointSet = true;
            } else {
                rectangleSelector.east = Math.max(tempCartographic.longitude, firstPoint.longitude);
                rectangleSelector.west = Math.min(tempCartographic.longitude, firstPoint.longitude);
                rectangleSelector.north = Math.max(tempCartographic.latitude, firstPoint.latitude);
                rectangleSelector.south = Math.min(tempCartographic.latitude, firstPoint.latitude);
                selector.show = true;
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE, Cesium.KeyboardEventModifier.SHIFT);

    var getSelectorLocation = new Cesium.CallbackProperty(function getSelectorLocation(time, result) {
        return Cesium.Rectangle.clone(rectangleSelector, result);
    }, false);

    screenSpaceEventHandler.setInputAction(function startClickShift() {
        mouseDown = true;
        selector.rectangle.coordinates = getSelectorLocation;
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN, Cesium.KeyboardEventModifier.SHIFT);

    screenSpaceEventHandler.setInputAction(function endClickShift() {
        mouseDown = false;
        firstPointSet = false;
        selector.rectangle.coordinates = rectangleSelector;
        cb && cb(rectangleSelector)
    }, Cesium.ScreenSpaceEventType.LEFT_UP, Cesium.KeyboardEventModifier.SHIFT);

    //Hide the selector by clicking anywhere
    screenSpaceEventHandler.setInputAction(function hideSelector() {
        selector.show = false;
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


    selector = viewer.entities.add({
        selectable: false,
        show: false,
        rectangle: {
            coordinates: getSelectorLocation,
            material: Cesium.Color.RED.withAlpha(0.5)
        }
    });
}