"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 events = __importStar(require("events"));
const conversation_1 = __importDefault(require("./conversation"));
const text_formatter_1 = __importDefault(require("./card-output/text-formatter"));
class StatelessConversationDelegate {
    constructor(conversationId) {
        this._buffer = [];
        this._askSpecial = null;
        this._id = conversationId;
    }
    flush() {
        const buffer = this._buffer;
        const askSpecial = this._askSpecial;
        this._buffer = [];
        this._askSpecial = null;
        return {
            conversationId: this._id,
            messages: buffer,
            askSpecial: askSpecial,
        };
    }
    setHypothesis() {
        // ignore
    }
    setExpected(what) {
        assert_1.default(this._askSpecial === null);
        this._askSpecial = what;
    }
    async addMessage(message) {
        this._buffer.push(message);
    }
}
class Assistant extends events.EventEmitter {
    constructor(engine, nluModelUrl) {
        super();
        this._engine = engine;
        this._formatter = new text_formatter_1.default(engine.platform.locale, engine.platform.timezone, engine.schemas);
        this._nluModelUrl = nluModelUrl;
        this._outputs = new Set;
        this._conversations = new Map;
        this._lastConversation = null;
    }
    async start() { }
    async stop() { }
    async converse(command, user, conversationId) {
        const conversation = await this.getOrOpenConversation(conversationId, user, {
            showWelcome: false,
            anonymous: false,
            debug: true
        });
        const delegate = new StatelessConversationDelegate(conversationId);
        await conversation.addOutput(delegate, false);
        switch (command.type) {
            case 'command':
                await conversation.handleCommand(command.text);
                break;
            case 'parsed':
                await conversation.handleParsedCommand(command.json, command.title);
                break;
            case 'tt':
                await conversation.handleThingTalk(command.code);
                break;
        }
        await conversation.removeOutput(delegate);
        const result = delegate.flush();
        return result;
    }
    addNotificationOutput(output) {
        this._outputs.add(output);
    }
    removeNotificationOutput(output) {
        this._outputs.delete(output);
    }
    async notifyAll(appId, icon, outputType, outputValue) {
        const promises = [];
        if (this._outputs.size > 0) {
            const messages = await this._formatter.formatForType(outputType, outputValue, 'messages');
            for (const out of this._outputs.values()) {
                promises.push(out.notify({
                    appId: appId,
                    icon: icon,
                    raw: outputValue,
                    type: outputType,
                    formatted: messages
                }));
            }
        }
        for (const conv of this._conversations.values())
            promises.push(conv.notify(appId, icon, outputType, outputValue));
        await Promise.all(promises);
    }
    async notifyErrorAll(appId, icon, error) {
        const promises = [];
        for (const out of this._outputs.values()) {
            promises.push(out.notifyError({
                appId: appId,
                icon: icon,
                error: error
            }));
        }
        for (const conv of this._conversations.values())
            promises.push(conv.notifyError(appId, icon, error));
        await Promise.all(promises);
    }
    getConversation(id) {
        if (id !== undefined && this._conversations.has(id))
            return this._conversations.get(id);
        else
            return this._lastConversation;
    }
    async getOrOpenConversation(id, user, options) {
        if (this._conversations.has(id))
            return this._conversations.get(id);
        options = options || {};
        if (!options.nluServerUrl)
            options.nluServerUrl = this._nluModelUrl;
        const conv = this.openConversation(id, user, options);
        await conv.start();
        return conv;
    }
    openConversation(id, user, options) {
        this._conversations.delete(id);
        options = options || {};
        if (!options.nluServerUrl)
            options.nluServerUrl = this._nluModelUrl;
        let deleteWhenInactive = options.deleteWhenInactive;
        if (deleteWhenInactive === undefined)
            deleteWhenInactive = true;
        const conv = new conversation_1.default(this._engine, id, user, options);
        conv.on('active', () => {
            this._lastConversation = conv;
        });
        if (deleteWhenInactive) {
            conv.on('inactive', () => {
                if (this._conversations.get(conv.id) === conv)
                    this._conversations.delete(conv.id);
            });
        }
        this._lastConversation = conv;
        this._conversations.set(id, conv);
        return conv;
    }
    closeConversation(id) {
        this._conversations.delete(id);
    }
}
exports.default = Assistant;
//# sourceMappingURL=dispatcher.js.map