'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
require('../../../composables/index.js');
var cesiumProps = require('../../../utils/cesium-props.js');
var util = require('../../../utils/util.js');
var DynamicOverlay = require('../../../shared/src/DynamicOverlay.js');
var cesiumHelpers = require('../../../utils/cesium-helpers.js');
var cloneDeep = require('lodash/cloneDeep');
var differenceBy = require('lodash/differenceBy');
var remove = require('lodash/remove');
var vm = require('../../../utils/private/vm.js');
var index = require('../../../composables/use-common/index.js');
var shared = require('@vue/shared');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(cloneDeep);
var differenceBy__default = /*#__PURE__*/_interopDefaultLegacy(differenceBy);
var remove__default = /*#__PURE__*/_interopDefaultLegacy(remove);

var OverlayDynamic = vue.defineComponent({
  name: "VcOverlayDynamic",
  props: {
    ...cesiumProps.show,
    name: {
      type: String,
      default: "__vc__overlay__dynamic__"
    },
    startTime: {
      type: [Object, String]
    },
    stopTime: {
      type: [Object, String]
    },
    currentTime: {
      type: [Object, String]
    },
    clockRange: {
      type: Number,
      default: 0
    },
    clockStep: {
      type: Number,
      default: 1
    },
    shouldAnimate: {
      type: Boolean,
      default: true
    },
    canAnimate: {
      type: Boolean,
      default: true
    },
    multiplier: {
      type: Number,
      default: 1
    },
    dynamicOverlays: {
      type: Array,
      default: () => []
    },
    defaultInterval: {
      type: Number,
      default: 3
    }
  },
  emits: [
    "beforeLoad",
    "ready",
    "destroyed",
    "update:currentTime",
    "update:shouldAnimate",
    "update:canAnimate",
    "update:clockRange",
    "update:clockStep",
    "update:multiplier",
    "update:startTime",
    "update:stopTime"
  ],
  setup(props, ctx) {
    const instance = vue.getCurrentInstance();
    instance.cesiumClass = "VcOverlayDynamic";
    instance.cesiumEvents = [];
    const commonState = index["default"](props, ctx, instance);
    if (commonState === void 0) {
      return;
    }
    const { $services } = commonState;
    const overlays = vue.ref([]);
    const restoreClockOpts = vue.ref({});
    const { emit } = ctx;
    let unwatchFns = [];
    unwatchFns.push(vue.watch(() => props.show, (val) => {
      const datasource = instance.cesiumObject;
      datasource && (datasource.show = val);
    }));
    unwatchFns.push(vue.watch(() => props.name, (val) => {
      const datasource = instance.cesiumObject;
      datasource && (datasource.name = val);
    }));
    unwatchFns.push(vue.watch(() => props.startTime, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer) && val) {
        viewer.clock.startTime = cesiumHelpers.makeJulianDate(val);
      }
    }));
    unwatchFns.push(vue.watch(() => props.stopTime, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer) && val) {
        viewer.clock.stopTime = cesiumHelpers.makeJulianDate(val);
      }
    }));
    unwatchFns.push(vue.watch(() => props.currentTime, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer) && val) {
        viewer.clock.currentTime = cesiumHelpers.makeJulianDate(val);
      }
    }));
    unwatchFns.push(vue.watch(() => props.multiplier, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer)) {
        viewer.clock.multiplier = val;
      }
    }));
    unwatchFns.push(vue.watch(() => props.clockStep, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer)) {
        viewer.clock.clockStep = val;
      }
    }));
    unwatchFns.push(vue.watch(() => props.clockRange, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer)) {
        viewer.clock.clockRange = val;
      }
    }));
    unwatchFns.push(vue.watch(() => props.canAnimate, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer)) {
        viewer.clock.canAnimate = val;
      }
    }));
    unwatchFns.push(vue.watch(() => props.shouldAnimate, (val) => {
      const { viewer } = $services;
      if (Cesium.defined(viewer)) {
        viewer.clock.shouldAnimate = val;
      }
    }));
    unwatchFns.push(vue.watch(() => cloneDeep__default["default"](props.dynamicOverlays), (newVal, oldVal) => {
      if (!instance.mounted) {
        return;
      }
      const datasource = instance.cesiumObject;
      if (newVal.length === oldVal.length) {
        const modifies = [];
        for (let i = 0; i < newVal.length; i++) {
          let testReplace = function(key, value) {
            if (key !== "nodeTransformations") {
              return value;
            }
          };
          const options = newVal[i];
          const oldOptions = oldVal[i];
          if (JSON.stringify(options, testReplace) !== JSON.stringify(oldOptions, testReplace)) {
            modifies.push({
              newOptions: options,
              oldOptions
            });
          }
        }
        modifies.forEach((v) => {
          const modifyEntity = datasource.entities.getById(v.oldOptions.id);
          if (v.oldOptions.id === v.newOptions.id) {
            modifyEntity && Object.keys(v.newOptions).forEach((prop) => {
              if (v.oldOptions[prop] !== v.newOptions[prop]) {
                modifyEntity[prop] = commonState.transformProp(prop, v.newOptions[prop]);
              }
            });
          } else {
            if (modifyEntity) {
              datasource.entities.remove(modifyEntity);
              remove__default["default"](overlays.value, (overlay) => overlay.id === modifyEntity.id);
              const entityOptions = v.newOptions;
              addDynamicOverlays(datasource, [entityOptions]);
            }
          }
        });
      } else {
        const adds = differenceBy__default["default"](newVal, oldVal, "id");
        const deletes = differenceBy__default["default"](oldVal, newVal, "id");
        const deletedEntities = [];
        for (let i = 0; i < deletes.length; i++) {
          const deleteEntity = datasource.entities.getById(deletes[i].id);
          deletedEntities.push(deleteEntity);
        }
        deletedEntities.forEach((v) => {
          datasource.entities.remove(v);
          remove__default["default"](overlays.value, (overlay) => overlay.id === v.id);
        });
        addDynamicOverlays(datasource, adds);
      }
    }, {
      deep: true
    }));
    instance.createCesiumObject = async () => {
      return new Cesium.CustomDataSource(props.name);
    };
    const onClockTick = (clock) => {
      let listener = vm.getInstanceListener(instance, "update:currentTime");
      listener && emit("update:currentTime", clock.currentTime);
      listener = vm.getInstanceListener(instance, "update:shouldAnimate");
      listener && emit("update:shouldAnimate", clock.shouldAnimate);
      listener = vm.getInstanceListener(instance, "update:canAnimate");
      listener && emit("update:canAnimate", clock.canAnimate);
      listener = vm.getInstanceListener(instance, "update:clockRange");
      listener && emit("update:clockRange", clock.clockRange);
      listener = vm.getInstanceListener(instance, "update:clockStep");
      listener && emit("update:clockStep", clock.clockStep);
      listener = vm.getInstanceListener(instance, "update:multiplier");
      listener && emit("update:multiplier", clock.multiplier);
      listener = vm.getInstanceListener(instance, "update:startTime");
      listener && emit("update:startTime", clock.startTime);
      listener = vm.getInstanceListener(instance, "update:stopTime");
      listener && emit("update:stopTime", clock.stopTime);
    };
    const addDynamicOverlays = (datasource, dynamicOverlays) => {
      for (let i = 0; i < dynamicOverlays.length; i++) {
        const entityOptions = dynamicOverlays[i];
        const entityOptionsTransform = commonState.transformProps(entityOptions);
        const dynamicOverlay = new DynamicOverlay["default"](entityOptionsTransform);
        overlays.value.push(dynamicOverlay);
        const entity = datasource.entities.add(dynamicOverlay._entity);
        entityOptionsTransform.sampledPositions.forEach((sampledPosition) => {
          if (Array.isArray(sampledPosition) || sampledPosition instanceof Cesium.Cartesian3) {
            dynamicOverlay.addPosition(sampledPosition, props.defaultInterval);
          } else if (shared.isPlainObject(sampledPosition)) {
            if (sampledPosition.time) {
              dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.time);
            } else if (sampledPosition.interval) {
              dynamicOverlay.addPosition(sampledPosition.position, sampledPosition.interval);
            }
          }
        });
        entityOptions.id !== entity.id && (entityOptions.id = entity.id);
        util.addCustomProperty(entity, entityOptionsTransform);
      }
    };
    instance.mount = async () => {
      const { viewer } = $services;
      const datasource = instance.cesiumObject;
      datasource.show = props.show;
      addDynamicOverlays(datasource, props.dynamicOverlays);
      return viewer.dataSources.add(datasource).then(() => {
        restoreClockOpts.value.startTime = viewer.clock.startTime;
        restoreClockOpts.value.stopTime = viewer.clock.stopTime;
        restoreClockOpts.value.currentTime = viewer.clock.currentTime;
        restoreClockOpts.value.multiplier = viewer.clock.multiplier;
        restoreClockOpts.value.clockStep = viewer.clock.clockStep;
        restoreClockOpts.value.clockRange = viewer.clock.clockRange;
        restoreClockOpts.value.canAnimate = viewer.clock.canAnimate;
        restoreClockOpts.value.shouldAnimate = viewer.clock.shouldAnimate;
        if (props.startTime) {
          viewer.clock.startTime = cesiumHelpers.makeJulianDate(props.startTime);
        }
        if (props.stopTime) {
          viewer.clock.stopTime = cesiumHelpers.makeJulianDate(props.stopTime);
        }
        if (props.currentTime) {
          viewer.clock.currentTime = cesiumHelpers.makeJulianDate(props.currentTime);
        }
        viewer.clock.multiplier = props.multiplier;
        viewer.clock.clockStep = props.clockStep;
        viewer.clock.clockRange = props.clockRange;
        viewer.clock.canAnimate = false;
        viewer.clock.shouldAnimate = props.shouldAnimate;
        viewer.clock.onTick.addEventListener(onClockTick);
        return true;
      });
    };
    instance.unmount = async () => {
      const { viewer } = $services;
      const datasource = instance.cesiumObject;
      viewer.dataSources.remove(datasource, true);
      viewer.clock.startTime = restoreClockOpts.value.startTime;
      viewer.clock.stopTime = restoreClockOpts.value.stopTime;
      viewer.clock.multiplier = restoreClockOpts.value.multiplier;
      viewer.clock.clockStep = restoreClockOpts.value.clockStep;
      viewer.clock.clockRange = restoreClockOpts.value.clockRange;
      viewer.clock.canAnimate = restoreClockOpts.value.canAnimate;
      viewer.clock.shouldAnimate = restoreClockOpts.value.shouldAnimate;
      overlays.value.length = 0;
      viewer.clock.onTick.removeEventListener(onClockTick);
      return true;
    };
    vue.onUnmounted(() => {
      unwatchFns.forEach((item) => item());
      unwatchFns = [];
    });
    Object.assign(instance.proxy, { overlays });
    return () => {
      var _a;
      return vue.createCommentVNode(util.kebabCase(((_a = instance.proxy) == null ? void 0 : _a.$options.name) || ""));
    };
  }
});

exports["default"] = OverlayDynamic;
//# sourceMappingURL=index.js.map
