"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 string_interp_1 = __importDefault(require("string-interp"));
const I18n = __importStar(require("../../i18n"));
const format_objects_1 = require("./format_objects");
/**
 * An object that is able to convert structured ThingTalk results
 * into interactive cards suitable to supplement text or speech output.
 */
class CardFormatter extends string_interp_1.default.Formatter {
    /**
     * Construct a new formatter.
     *
     * @param locale - the user's locale, as a BCP47 tag
     * @param timezone - the user's timezone, as a string in the IANA timezone database (e.g. America/Los_Angeles, Europe/Rome)
     * @param schemaRetriever - the interface to access Thingpedia for formatting information
     */
    constructor(locale, timezone, schemaRetriever) {
        super(locale, timezone);
        this._schemas = schemaRetriever;
        this._ = I18n.get(locale).gettext;
    }
    replaceInString(str, argMap) {
        if (typeof str !== 'string')
            return null;
        const replaced = string_interp_1.default(str, argMap, {
            locale: this._locale,
            timezone: this._timezone,
            nullReplacement: this._("N/A")
        });
        if (replaced === undefined)
            return null;
        return replaced;
    }
    async formatForType(outputType, outputValue, options) {
        // apply masquerading for @remote.receive
        if (outputType === 'org.thingpedia.builtin.thingengine.remote:receive')
            outputType = String(outputValue.__kindChannel);
        if (outputType === null)
            return [];
        // ignore multiple output types (legacy join)
        if (outputType.indexOf('+') >= 0) {
            const types = outputType.split('+');
            outputType = types[types.length - 1];
        }
        const aggregation = /^([a-zA-Z]+)\(([^)]+)\)$/.exec(outputType);
        if (aggregation !== null)
            return [];
        const [kind, function_name] = outputType.split(':');
        const formatspec = (await this._schemas.getFormatMetadata(kind, function_name));
        return this._normalize(formatspec.map((f, i) => {
            if (typeof f === 'string')
                f = { type: 'text', text: f };
            if (f.type === 'text') {
                // when this method is called to supplement text output, we pass removeText=true and ignore
                // any purely textual output in the #_[formatted] annotation
                // when this method is called to form notification or for $event, we pass removeText=false
                // and use the textual output in #_[formatted]
                //
                // FIXME text in #_[formatted] should be always removed and we should always use the
                // state machine and #_[result] to form the output text
                if (options.removeText)
                    return null;
                else
                    return this.replaceInString(f.text, outputValue);
            }
            const formatType = format_objects_1.FORMAT_TYPES[f.type];
            if (!formatType) {
                console.log(`WARNING: unrecognized format type ${f.type}`);
                return null;
            }
            const obj = new formatType(f);
            obj.replaceParameters(this, outputValue);
            if (!obj.isValid())
                return null;
            return obj;
        }));
    }
    _normalize(formatted) {
        // filter out null/undefined in the array
        const filtered = formatted.filter((formatted) => !format_objects_1.isNull(formatted));
        // flatten formatted (returning array in function causes nested array)
        const empty = [];
        return empty.concat(...filtered);
    }
}
exports.default = CardFormatter;
//# sourceMappingURL=card-formatter.js.map