"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const integration_base_1 = require("@things-factory/integration-base");
const utils_1 = require("@things-factory/utils");
const get_tracking_workspace_1 = require("./get-tracking-workspace");
function getObjectState(domain, objectId) {
    var workspace = (0, get_tracking_workspace_1.getTrackingWorkspace)(domain);
    if (!workspace) {
        /* TODO workspace가 없는 경우와, object가 detect되지 않은 상태에 대한 구분처리가 필요하다. */
        return {};
    }
    var { engine } = workspace;
    var { trackingStorage } = engine;
    return trackingStorage.getObjectState(objectId);
}
const isValidPose = pose => {
    if (!pose) {
        return false;
    }
    var { x, y, z, u, v, w } = pose;
    return [x, y, z, u, v, w].findIndex(x => isNaN(x) || x === null || x === '') === -1;
};
async function TrackableObjectWaitForMove(step, { root, data, logger, domain }) {
    var { name: stepName, connection, params } = step;
    var { duration = 1000 } = params || {};
    var object = integration_base_1.ConnectionManager.getConnectionInstanceByName(domain, connection) || {};
    if (!object) {
        throw new Error(`no connection : ${connection}`);
    }
    var { endpoint: objectId } = object;
    var lastStatus = data[stepName];
    if (!lastStatus) {
        lastStatus = getObjectState(domain, objectId);
    }
    var { movedAt: oldMovedAt } = lastStatus;
    while (true) {
        let state = root.getState();
        if (state == integration_base_1.ScenarioInstanceStatus.STARTED /* STARTED */) {
            let recentStatus = getObjectState(domain, objectId);
            let { pose, retention: newRetention, movedAt: newMovedAt } = recentStatus;
            if (newMovedAt !== oldMovedAt && newRetention > 0 && isValidPose(pose)) {
                lastStatus = recentStatus;
                break;
            }
            await (0, utils_1.sleep)(Number(duration));
        }
        else if (state == integration_base_1.ScenarioInstanceStatus.STOPPED /* PAUSED */) {
            await (0, utils_1.sleep)(Number(duration));
        }
        else {
            throw new Error('scenario stopped unexpectedly');
        }
    }
    return {
        data: lastStatus
    };
}
TrackableObjectWaitForMove.parameterSpec = [
    {
        type: 'number',
        name: 'duration',
        label: 'duration',
        placeholder: 'milli-seconds'
    }
];
TrackableObjectWaitForMove.help = 'robotics/task/trackable-object-wait-for-move';
integration_base_1.TaskRegistry.registerTaskHandler('trackable-object-wait-for-move', TrackableObjectWaitForMove);
//# sourceMappingURL=trackable-object-wait-for-move.js.map