"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 });
exports.negativeListProposalReply = exports.listProposalLearnMoreReply = exports.positiveListProposalReplyActionByName = exports.positiveListProposalReply = exports.makeListProposalReply = exports.addActionToListProposal = exports.checkListProposal = exports.listProposalKeyFn = exports.nameListKeyFn = void 0;
const assert_1 = __importDefault(require("assert"));
const thingtalk_1 = require("thingtalk");
const C = __importStar(require("../ast_manip"));
const state_manip_1 = require("../state_manip");
const common_1 = require("./common");
const refinement_helpers_1 = require("./refinement-helpers");
function nameListKeyFn(list) {
    const schema = list.ctx.currentFunction;
    return {
        functionName: schema.qualifiedName,
        idType: schema.getArgType('id'),
        id0: list.ctx.key.id0,
        id1: list.ctx.key.id1,
        id2: list.ctx.key.id2,
    };
}
exports.nameListKeyFn = nameListKeyFn;
function listProposalKeyFn([results, info, action, hasLearnMore]) {
    return {
        idType: results[0].value.id.getType(),
        queryName: info ? info.schema.qualifiedName : null,
        actionName: action ? action.schema.qualifiedName : null,
    };
}
exports.listProposalKeyFn = listProposalKeyFn;
function checkListProposal(nameList, info, hasLearnMore) {
    const { ctx, results } = nameList;
    const resultType = results[0].value.id.getType();
    if (info !== null) {
        const idType = info.schema.getArgType('id');
        if (!idType || !idType.equals(resultType))
            return null;
        // check that the filter uses the right set of parameters
        const resultInfo = ctx.resultInfo;
        if (resultInfo.projection !== null) {
            // check that all projected names are present
            for (const name of resultInfo.projection) {
                if (!info.has(name))
                    return null;
            }
        }
        for (const result of results) {
            if (!common_1.isInfoPhraseCompatibleWithResult(result, info))
                return null;
        }
    }
    else {
        if (ctx.resultInfo.projection !== null)
            return null;
    }
    const action = ctx.nextInfo && ctx.nextInfo.isAction ? C.getInvocation(ctx.next) : null;
    return [results, info, action, hasLearnMore];
}
exports.checkListProposal = checkListProposal;
function addActionToListProposal(nameList, action) {
    const { ctx, results } = nameList;
    if (ctx.resultInfo.projection !== null)
        return null;
    const resultType = results[0].value.id.getType();
    if (!C.hasArgumentOfType(action, resultType))
        return null;
    const ctxAction = ctx.nextInfo && ctx.nextInfo.isAction ? C.getInvocation(ctx.next) : null;
    if (ctxAction && !C.isSameFunction(ctxAction.schema, action.schema))
        return null;
    return [results, null, action, false];
}
exports.addActionToListProposal = addActionToListProposal;
function makeListProposalReply(ctx, proposal) {
    const [results, /*info*/ , action, hasLearnMore] = proposal;
    const options = {
        numResults: results.length
    };
    if (action || hasLearnMore)
        options.end = false;
    const dialogueAct = results.length === 2 ? 'sys_recommend_two' : 'sys_recommend_three';
    if (action === null)
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, dialogueAct, null), proposal, null, options);
    else
        return state_manip_1.makeAgentReply(ctx, state_manip_1.addAction(ctx, dialogueAct, action, 'proposed'), proposal, null, options);
}
exports.makeListProposalReply = makeListProposalReply;
function positiveListProposalReply(loader, ctx, [name, acceptedAction, mustHaveAction]) {
    // if actionProposal === null the flow is roughly
    //
    // U: hello i am looking for a restaurant
    // A: how about the ... or the ... ?
    // U: I like the ... bla
    //
    // in this case, the agent should hit the "... is a ... restaurant in the ..."
    // we treat it as "execute" dialogue act and add a filter that causes the program to return a single result
    const proposal = ctx.aux;
    const [results, /*info*/ , actionProposal] = proposal;
    let good = false;
    for (const result of results) {
        if (result.value.id.equals(name)) {
            good = true;
            break;
        }
    }
    if (!good)
        return null;
    if (acceptedAction === null)
        acceptedAction = actionProposal;
    if (acceptedAction === null) {
        if (mustHaveAction)
            return null;
        const currentStmt = ctx.current.stmt;
        const currentTable = currentStmt.expression;
        const namefilter = new thingtalk_1.Ast.BooleanExpression.Atom(null, 'id', '==', name);
        const newTable = refinement_helpers_1.queryRefinement(currentTable, namefilter, (one, two) => new thingtalk_1.Ast.BooleanExpression.And(null, [one, two]), null);
        if (newTable === null)
            return null;
        return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
    }
    else {
        if (actionProposal !== null && !C.isSameFunction(actionProposal.schema, acceptedAction.schema))
            return null;
        // do not consider a phrase of the form "play X" to be "accepting the action by name"
        // if the action auto-confirms, because the user is likely playing something else
        if (acceptedAction && name) {
            const confirm = loader.ttUtils.normalizeConfirmAnnotation(acceptedAction.schema);
            if (confirm === 'auto')
                return null;
        }
        const chainParam = common_1.findChainParam(results[0], acceptedAction);
        if (!chainParam)
            return null;
        return state_manip_1.addActionParam(ctx, 'execute', acceptedAction, chainParam, name, 'accepted');
    }
}
exports.positiveListProposalReply = positiveListProposalReply;
function positiveListProposalReplyActionByName(loader, ctx, action) {
    const proposal = ctx.aux;
    const [results,] = proposal;
    let name = null;
    const acceptedAction = action.clone();
    const idType = results[0].value.id.getType();
    // find the chain parameter for the action, extract the name, and set the param to undefined
    // as the rest of the code expects
    for (const in_param of acceptedAction.in_params) {
        const arg = action.schema.getArgument(in_param.name);
        assert_1.default(arg);
        if (arg.type.equals(idType)) {
            name = in_param.value;
            in_param.value = new thingtalk_1.Ast.Value.Undefined(true);
            break;
        }
    }
    if (!name)
        return null;
    return positiveListProposalReply(loader, ctx, [name, acceptedAction, false]);
}
exports.positiveListProposalReplyActionByName = positiveListProposalReplyActionByName;
function negativeListProposalReply(ctx, [preamble, request]) {
    if (!((preamble === null || preamble instanceof thingtalk_1.Ast.FilterExpression) &&
        (request === null || request instanceof thingtalk_1.Ast.FilterExpression)))
        return null;
    const proposal = ctx.aux;
    const [results, info] = proposal;
    const proposalType = results[0].value.id.getType();
    request = refinement_helpers_1.combinePreambleAndRequest(preamble, request, info, proposalType);
    if (request === null)
        return null;
    return refinement_helpers_1.proposalReply(ctx, request, refinement_helpers_1.refineFilterToAnswerQuestionOrChangeFilter);
}
exports.negativeListProposalReply = negativeListProposalReply;
function listProposalLearnMoreReply(ctx, name) {
    // note: a learn more from a list proposal is different than a learn_more from a recommendation
    // in a recommendation, there is no change to the program, and the agent replies "what would
    // you like to know"
    // in a list proposal, we add a filter "id == "
    const proposal = ctx.aux;
    const [results,] = proposal;
    let good = false;
    for (const result of results) {
        if (result.value.id.equals(name)) {
            good = true;
            break;
        }
    }
    if (!good)
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    const namefilter = new thingtalk_1.Ast.BooleanExpression.Atom(null, 'id', '==', name);
    const newTable = refinement_helpers_1.queryRefinement(currentTable, namefilter, (one, two) => new thingtalk_1.Ast.BooleanExpression.And(null, [one, two]), null);
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.listProposalLearnMoreReply = listProposalLearnMoreReply;
//# sourceMappingURL=list-proposal.js.map