"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: Silei Xu <silei@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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.execute = exports.initArgparse = void 0;
const readline = __importStar(require("readline"));
const Tp = __importStar(require("thingpedia"));
const ThingTalk = __importStar(require("thingtalk"));
const ParserClient = __importStar(require("../../../lib/prediction/parserclient"));
const ThingTalkUtils = __importStar(require("../../../lib/utils/thingtalk"));
const utils_1 = require("./utils");
class CommandLineHandler {
    constructor(rl, options) {
        this._rl = rl;
        this._rl.on('line', this._onLine.bind(this));
        this._rl.on('SIGINT', this._quit.bind(this));
        this._tpClient = new Tp.FileClient(options);
        this._schemas = new ThingTalk.SchemaRetriever(this._tpClient, null, true);
        this._parser = ParserClient.get(options.server, 'en-US');
    }
    async start() {
        await this._parser.start();
        this._rl.prompt();
    }
    async _quit() {
        console.log('Bye\n');
        await this._parser.stop();
        this._rl.close();
    }
    async _parseCommand(line) {
        const parsed = await this._parser.sendUtterance(line, /* context */ undefined, /* contextEntities */ {}, {
            tokenized: false,
            skip_typechecking: true
        });
        if (parsed.candidates.length === 0) {
            console.log('Failed to parse the query. Please try something different');
            return;
        }
        const candidates = await ThingTalkUtils.parseAllPredictions(parsed.candidates, parsed.entities, {
            thingpediaClient: this._tpClient,
            schemaRetriever: this._schemas
        });
        const program = candidates[0];
        if (program && program instanceof ThingTalk.Ast.Program) {
            console.log(`ThingTalk: ${program.prettyprint()}`);
        }
        else {
            console.log(`The model failed to make a prediction that is syntactically correct, please try something else`);
            console.error(`Prediction: ${parsed.candidates[0].code.join(' ')}`);
            return;
        }
        try {
            const sparql = ThingTalk.Helper.toSparql(program);
            console.log(`SPARQL: ${sparql}`);
            console.log(`Querying Wikidata Server... (this may take up to 30 seconds)`);
            const results = await utils_1.wikidataQuery(sparql);
            console.log(`Answer:`);
            for (const result of results)
                console.log(result);
        }
        catch (e) {
            if (e.code)
                console.error('Something went wrong when querying Wikidata server, check the log for details.');
            else
                console.error(e);
        }
    }
    async _onLine(line) {
        await this._parseCommand(line);
        this._rl.prompt();
    }
}
function initArgparse(subparsers) {
    const parser = subparsers.add_parser('wikidata-demo', {
        add_help: true,
        description: "Demo a Wikidata skill."
    });
    parser.add_argument('-l', '--locale', {
        required: false,
        default: 'en-US',
        help: `BGP 47 locale tag of the language to use for the assistant (defaults to 'en-US', English)`
    });
    parser.add_argument('--manifest', {
        required: true,
        help: 'URL of wikidata manifest to use.'
    });
    parser.add_argument('--model', {
        required: true,
        help: 'NLP server URL to use for NLU (can be a file:/// URL).'
    });
}
exports.initArgparse = initArgparse;
async function execute(args) {
    const options = {
        locale: args.locale,
        thingpedia: args.manifest,
        server: args.model
    };
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    rl.setPrompt('$ ');
    const handler = new CommandLineHandler(rl, options);
    await handler.start();
}
exports.execute = execute;
//# sourceMappingURL=demo.js.map