"use strict";
// -*- mode: typescript; indent-tabs-mode: nil; js-basic-offset: 4 -*-
//
// This file is part of Genie
//
// Copyright 2020 The Board of Trustees of the Leland Stanford Junior University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Giovanni Campagna <gcampagn@cs.stanford.edu>
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const ThingTalk = __importStar(require("thingtalk"));
const thingtalk_1 = require("thingtalk");
const trigger_runner_1 = __importDefault(require("./trigger_runner"));
const timers_1 = require("./timers");
const device_view_1 = __importDefault(require("../devices/device_view"));
const text_formatter_1 = __importDefault(require("../../dialogue-agent/card-output/text-formatter"));
function extendParams(output, input) {
    for (const key in input) {
        if (Object.prototype.hasOwnProperty.call(output, key))
            continue;
        output[key] = input[key];
    }
}
function recursivelyComputeOutputType(kind, expr) {
    if (expr instanceof thingtalk_1.Ast.InvocationExpression)
        return kind + ':' + expr.invocation.channel;
    if (expr instanceof thingtalk_1.Ast.ChainExpression)
        return expr.expressions.map((exp) => recursivelyComputeOutputType(kind, exp)).join('+');
    if (expr instanceof thingtalk_1.Ast.AggregationExpression)
        return expr.operator + '(' + recursivelyComputeOutputType(kind, expr.expression) + ')';
    if ('expression' in expr) // projection, index, slice
        return recursivelyComputeOutputType(kind, expr.expression);
    throw new TypeError('Invalid query expression ' + expr);
}
/**
 * Wrap a ThingTalk statement and provide access to the Engine.
 *
 * This is an implementation of {@link external:thingtalk.ExecEnvironment}
 * suitable for running with the Almond engine.
 *
 * @package
 */
class ExecWrapper extends thingtalk_1.ExecEnvironment {
    constructor(engine, app, output) {
        super();
        this.format = new text_formatter_1.default(engine.platform.locale, engine.platform.timezone, engine.schemas);
        this.engine = engine;
        this.app = app;
        this._programId = new ThingTalk.Builtin.Entity(this.app.uniqueId, null);
        this._outputDelegate = output;
        this._trigger = null;
        this._execCache = [];
        this._hooks = [];
    }
    setOutput(delegate) {
        this._outputDelegate = delegate;
    }
    get program_id() {
        return this._programId;
    }
    endProgram() {
        if (this._trigger)
            this._trigger.end();
        // otherwise just wait for the query/action to end
    }
    stopTrigger() {
        if (this._trigger)
            this._trigger.stop();
    }
    _wrapClearCache(asyncIterable) {
        const self = this;
        return {
            async next() {
                const value = await asyncIterable.next();
                self.clearGetCache();
                return value;
            }
        };
    }
    loadContext() {
        throw new Error('$context is not implemented');
        //return this.engine.platform.loadContext(info);
    }
    invokeTimer(base, interval, frequency) {
        const trigger = new timers_1.Timer(base, interval, frequency);
        this._trigger = trigger;
        trigger.start();
        return this._wrapClearCache(trigger);
    }
    invokeAtTimer(time, expiration_date) {
        const trigger = new timers_1.AtTimer(time, expiration_date);
        this._trigger = trigger;
        trigger.start();
        return this._wrapClearCache(trigger);
    }
    invokeMonitor(kind, attrs, fname, params, hints) {
        const trigger = new trigger_runner_1.default(this, new device_view_1.default(this.engine.devices, kind, attrs), fname, params, hints);
        this._trigger = trigger;
        trigger.start();
        return this._wrapClearCache(trigger);
    }
    _findInCache(kindKey, fnameKey, params) {
        for (const cached of this._execCache) {
            const [kind, fname, cachedparams, result] = cached;
            if (kind === kindKey && fname === fnameKey &&
                ThingTalk.Builtin.equality(cachedparams, params))
                return result;
        }
        return undefined;
    }
    clearGetCache() {
        this._execCache = [];
    }
    _getDevices(kind, attrs) {
        const deviceView = new device_view_1.default(this.engine.devices, kind, attrs, false);
        deviceView.start();
        return deviceView.values();
    }
    addExitProcedureHook(hook) {
        this._hooks.push(hook);
    }
    async exitProcedure(procid, procname) {
        await super.exitProcedure(procid, procname);
        for (const hook of this._hooks)
            await hook();
        this._hooks = [];
    }
    async *invokeQuery(kind, attrs, fname, params, hints) {
        const devices = this._getDevices(kind, attrs);
        let promises;
        const cached = this._findInCache(kind, fname, params);
        if (cached) {
            promises = cached;
        }
        else {
            const js_function_name = 'get_' + fname;
            promises = devices.map(async (d) => {
                return d[js_function_name](params, hints, this);
            });
            // cache now, rather than when the query completes, because ThingTalk might
            // invoke multiple queries in parallel
            this._execCache.push([kind, fname, params, promises]);
        }
        for (let i = 0; i < promises.length; i++) {
            const list = await promises[i];
            const device = devices[i];
            const outputType = device.kind + ':' + fname;
            for await (const element of list) {
                extendParams(element, params);
                yield [outputType, element];
            }
        }
    }
    async *invokeDBQuery(kind, attrs, query) {
        const devices = this._getDevices(kind, attrs); // FIXME
        const command = query.statements[0];
        assert_1.default(command instanceof thingtalk_1.Ast.ExpressionStatement);
        for (const device of devices) {
            const outputType = recursivelyComputeOutputType(device.kind, command.expression);
            for await (const result of device.query(query, this))
                yield [outputType, result];
        }
    }
    readState(stateId) {
        return this.app.readState(stateId);
    }
    writeState(stateId, state) {
        return this.app.writeState(stateId, state);
    }
    async *invokeAction(kind, attrs, fname, params) {
        const devices = this._getDevices(kind, attrs);
        const js_function_name = 'do_' + fname;
        for (const d of devices) {
            const outputType = d.kind + ':action/' + fname;
            let result = await d[js_function_name](params, this);
            if (typeof result === 'object' && result !== null) {
                extendParams(result, params);
            }
            else if (typeof result !== 'undefined') {
                console.error(`${outputType} returned a value that is not an object and not undefined; this is deprecated and might break`);
                result = undefined;
            }
            if (result)
                yield [outputType, result];
        }
    }
    get icon() {
        return this.app.icon;
    }
    async reportError(message, error) {
        // cancellation errors should bubble up
        if (error.code === 'ECANCELLED')
            throw error;
        console.error(message, error);
        this.app.setError(error);
        await this._outputDelegate.notifyError(error);
    }
    async output(outputType, outputValues) {
        await this._outputDelegate.output(outputType, outputValues);
    }
    async formatEvent(outputType, output, hint) {
        return String(await this.format.formatForType(outputType, output, hint));
    }
}
exports.default = ExecWrapper;
//# sourceMappingURL=exec_wrapper.js.map