var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { getOrRegisterPlainVariable } from '../shared/interactivity/plain-variable';
import { UserError } from '../types/core';
/**
 * Constant to replace with the input value.
 */
export const INPUT = '__dara_input__';
/**
 * Constant to signify the actions hould negate the previous variable value.
 */
export const TOGGLE = '__dara_toggle__';
/**
 * Front-end handler for UpdateVariable action.
 */
const UpdateVariable = (ctx, actionImpl) => __awaiter(void 0, void 0, void 0, function* () {
    if (actionImpl.variable.__typename !== 'Variable') {
        throw new UserError('UpdateVariable action only supports Variables');
    }
    const varAtom = getOrRegisterPlainVariable(actionImpl.variable, ctx.wsClient, ctx.taskCtx, ctx.extras);
    let newValue;
    if (actionImpl.value === INPUT) {
        newValue = ctx.input;
    }
    else if (actionImpl.value === TOGGLE) {
        // normally we'd use the updater form here, but we need to know what value we're
        // toggling to emit the correct event, and the updater must be pure
        const value = yield ctx.snapshot.getLoadable(varAtom).toPromise();
        newValue = !value;
    }
    else {
        newValue = actionImpl.value;
    }
    ctx.set(varAtom, newValue);
    ctx.eventBus.publish('PLAIN_VARIABLE_LOADED', { variable: actionImpl.variable, value: newValue });
});
export default UpdateVariable;
//# sourceMappingURL=update-variable.js.map