"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.actionSuccessQuestion = exports.actionErrorChangeParam = exports.makeActionErrorPhrase = exports.checkActionErrorMessage = exports.checkThingpediaErrorMessage = exports.makeGenericActionSuccessPhrase = exports.makeCompleteActionSuccessPhrase = exports.makeThingpediaActionSuccessPhrase = exports.actionSuccessPhraseWithResultKeyFn = void 0;
const assert_1 = __importDefault(require("assert"));
const thingtalk_1 = require("thingtalk");
const C = __importStar(require("../ast_manip"));
const slot_bag_1 = require("../slot_bag");
const state_manip_1 = require("../state_manip");
const common_1 = require("./common");
function actionSuccessPhraseWithResultKeyFn([expression, bag]) {
    return {
        functionName: bag.schema.qualifiedName
    };
}
exports.actionSuccessPhraseWithResultKeyFn = actionSuccessPhraseWithResultKeyFn;
function makeThingpediaActionSuccessPhrase(ctx, info) {
    const results = ctx.results;
    if (!results || results.length !== 1)
        return null;
    const ctxInvocation = C.getInvocation(ctx.current);
    if (!C.isSameFunction(ctxInvocation.schema, info.schema))
        return null;
    const topResult = results[0];
    if (!common_1.isInfoPhraseCompatibleWithResult(topResult, info))
        return null;
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_success', null), info);
}
exports.makeThingpediaActionSuccessPhrase = makeThingpediaActionSuccessPhrase;
function makeCompleteActionSuccessPhrase(ctx, action, info) {
    const results = ctx.results;
    assert_1.default(results);
    // check the action is the same we actually executed, and all the parameters we're mentioning
    // match the actual parameters of the action
    let last;
    if (action instanceof thingtalk_1.Ast.ChainExpression)
        last = action.last;
    else
        last = action;
    assert_1.default(last instanceof thingtalk_1.Ast.InvocationExpression);
    const ctxInvocation = C.getInvocation(ctx.current);
    if (!C.isSameFunction(ctxInvocation.schema, action.schema))
        return null;
    for (const newParam of last.invocation.in_params) {
        if (newParam.value.isUndefined)
            continue;
        let found = false, wasParamPassing = false;
        for (const oldParam of ctxInvocation.in_params) {
            assert_1.default(!oldParam.value.isUndefined); // we ran the action, so it cannot have $? params
            if (newParam.name === oldParam.name) {
                if (newParam.value instanceof thingtalk_1.Ast.VarRefValue) {
                    // we're using a join to describe this action
                    // we don't need to check that the table is correct, because
                    // the table comes from a context phrase, but do check the action
                    // is correct
                    if (oldParam.value instanceof thingtalk_1.Ast.VarRefValue) {
                        wasParamPassing = true;
                        if (newParam.value.name !== oldParam.value.name)
                            return null;
                    }
                    else {
                        return null;
                    }
                }
                else {
                    // newParam is a constant, but oldParam might be a param passing
                    if (oldParam.value instanceof thingtalk_1.Ast.VarRefValue)
                        wasParamPassing = true;
                    else if (!newParam.value.equals(oldParam.value))
                        return null;
                }
                found = true;
                break;
            }
        }
        if (!found) {
            const arg = action.schema.getArgument(newParam.name);
            if (arg.is_input)
                return null;
            // if newParam is an output parameter that we appended to describe the result
            // of the action, we allow it to be missing from the action, and we'll check
            // against the result entry
        }
        if (!(newParam.value instanceof thingtalk_1.Ast.VarRefValue)) {
            // if we can't check in the result bag, and we didn't find a constant
            // to check against in the program, then this phrase is no good
            // because we're hallucinating the value
            if (results.length === 0 && (!found || wasParamPassing))
                return null;
            if (results.length > 1)
                return null;
            // if the parameter is a constant, check also the result entry, if we have one
            // this checks that input parameters are correct, if they were parameter passed
            // and checks that the output parameters are correct
            if (results.length >= 1) {
                const topResult = results[0];
                const resultValue = topResult.value[newParam.name];
                if (!resultValue)
                    return null;
                if (!resultValue.equals(newParam.value))
                    return null;
            }
        }
    }
    if (info !== null) {
        if (results.length < 1)
            return null;
        assert_1.default(info instanceof slot_bag_1.SlotBag);
        if (!results.every((r) => common_1.isInfoPhraseCompatibleWithResult(r, info)))
            return null;
    }
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_success', null), info);
}
exports.makeCompleteActionSuccessPhrase = makeCompleteActionSuccessPhrase;
function makeGenericActionSuccessPhrase(ctx) {
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_success', null), null);
}
exports.makeGenericActionSuccessPhrase = makeGenericActionSuccessPhrase;
function checkThingpediaErrorMessage(ctx, msg) {
    if (!C.isSameFunction(ctx.currentFunction, msg.bag.schema))
        return null;
    const error = ctx.error;
    if (!(error instanceof thingtalk_1.Ast.EnumValue) || error.value !== msg.code)
        return null;
    const action = C.getInvocation(ctx.current);
    for (const in_param of action.in_params) {
        if (msg.bag.has(in_param.name) && !msg.bag.get(in_param.name).equals(in_param.value))
            return null;
    }
    return ctx;
}
exports.checkThingpediaErrorMessage = checkThingpediaErrorMessage;
function checkActionErrorMessage(ctx, action) {
    // check the action is the same we actually executed, and all the parameters we're mentioning
    // match the actual parameters of the action
    if (!C.isSameFunction(ctx.currentFunction, action.schema))
        return null;
    const ctxInvocation = C.getInvocation(ctx.current);
    for (const newParam of action.in_params) {
        if (newParam.value.isUndefined)
            continue;
        let found = false;
        for (const oldParam of ctxInvocation.in_params) {
            if (newParam.name === oldParam.name) {
                if (!newParam.value.equals(oldParam.value))
                    return null;
                found = true;
                break;
            }
        }
        if (!found)
            return null;
    }
    return ctx;
}
exports.checkActionErrorMessage = checkActionErrorMessage;
function makeActionErrorPhrase(ctx, questions) {
    const schema = ctx.currentFunction;
    for (const q of questions) {
        if (!C.isSameFunction(schema, q.schema))
            return null;
        const arg = schema.getArgument(q.name);
        if (!arg || !arg.is_input)
            return null;
    }
    assert_1.default(Array.isArray(questions));
    if (questions.length === 0)
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_error', null));
    if (questions.length === 1) {
        const type = schema.getArgType(questions[0].name);
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_error_question', questions.map((q) => q.name)), null, type);
    }
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_action_error_question', questions.map((q) => q.name)));
}
exports.makeActionErrorPhrase = makeActionErrorPhrase;
function actionErrorChangeParam(ctx, answer) {
    const schema = ctx.currentFunction;
    const questions = ctx.state.dialogueActParam || [];
    let ipslot;
    if (answer instanceof thingtalk_1.Ast.Value) {
        if (questions.length !== 1)
            return null;
        const arg = schema.getArgument(questions[0]);
        if (!arg || !arg.is_input || !arg.type.equals(answer.getType()))
            return null;
        ipslot = {
            schema,
            ptype: answer.getType(),
            ast: new thingtalk_1.Ast.InputParam(null, questions[0], answer)
        };
    }
    else {
        ipslot = answer;
        if (!C.isSameFunction(ipslot.schema, schema))
            return null;
    }
    const action = C.getInvocation(ctx.current);
    if (!action)
        return null;
    // shallow clone
    const clone = action.clone();
    state_manip_1.setOrAddInvocationParam(clone, ipslot.ast.name, ipslot.ast.value);
    return state_manip_1.replaceAction(ctx, 'execute', clone, 'accepted');
}
exports.actionErrorChangeParam = actionErrorChangeParam;
function actionSuccessQuestion(ctx, questions) {
    for (const q of questions) {
        if (!C.isSameFunction(q.schema, ctx.currentFunction))
            return null;
        const arg = ctx.currentFunction.getArgument(q.name);
        if (!arg || arg.is_input)
            return null;
    }
    return state_manip_1.makeSimpleState(ctx, 'action_question', questions.map((q) => q.name));
}
exports.actionSuccessQuestion = actionSuccessQuestion;
//# sourceMappingURL=action-results.js.map