"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.impreciseEmptySearchChangeRequest = exports.preciseEmptySearchChangeRequest = exports.makeEmptySearchError = void 0;
const thingtalk_1 = require("thingtalk");
const C = __importStar(require("../ast_manip"));
const state_manip_1 = require("../state_manip");
const refinement_helpers_1 = require("./refinement-helpers");
const common_1 = require("./common");
/**
 * Agent dialogue act: a search command returned no result.
 *
 * @param ctx - the current context
 * @param base - the base table used in the reply
 * @param question - a search question used in the reply
 */
function makeEmptySearchError(ctx, [base, question]) {
    if (base !== null && !C.isSameFunction(base.schema, ctx.currentTableFunction))
        return null;
    if (question !== null && !C.isSameFunction(ctx.currentTableFunction, question.schema))
        return null;
    let type, state;
    if (question !== null) {
        if (!isGoodEmptySearchQuestion(ctx, question))
            return null;
        const arg = ctx.currentTableFunction.getArgument(question.name);
        if (!arg)
            return null;
        type = arg.type;
        state = state_manip_1.makeSimpleState(ctx, 'sys_empty_search_question', [question.name]);
    }
    else {
        type = null;
        state = state_manip_1.makeSimpleState(ctx, 'sys_empty_search', null);
    }
    return state_manip_1.makeAgentReply(ctx, state, [base, question], type);
}
exports.makeEmptySearchError = makeEmptySearchError;
function isGoodEmptySearchQuestion(ctx, question) {
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    if (!common_1.isValidSearchQuestion(currentTable, [question]))
        return false;
    const ctxFilterTable = C.findFilterExpression(currentTable);
    if (!ctxFilterTable || !C.filterUsesParam(ctxFilterTable.filter, question.name))
        return false;
    return true;
}
function emptySearchChangePhraseCommon(ctx, newFilter) {
    const currentStmt = ctx.current.stmt;
    const currentExpression = currentStmt.expression;
    const newExpression = refinement_helpers_1.queryRefinement(currentExpression, newFilter, refinement_helpers_1.refineFilterToChangeFilter, null);
    if (newExpression === null)
        return null;
    // XXX: do we want to remove any sort/index?
    return state_manip_1.addQuery(ctx, 'execute', newExpression, 'accepted');
}
/**
 * User dialogue act: in response to an empty search, the user changes their constraints.
 *
 * The "precise" variant explicitly contains a reference to a table, which must be the same
 * as the context.
 */
function preciseEmptySearchChangeRequest(ctx, phrase) {
    if (!(phrase instanceof thingtalk_1.Ast.FilterExpression))
        return null;
    const [, param] = ctx.aux;
    if (!C.isSameFunction(ctx.currentTableFunction, phrase.schema))
        return null;
    if (param !== null && !C.filterUsesParam(phrase.filter, param.name))
        return null;
    return emptySearchChangePhraseCommon(ctx, phrase.filter);
}
exports.preciseEmptySearchChangeRequest = preciseEmptySearchChangeRequest;
/**
 * User dialogue act: in response to an empty search, the user changes their constraints.
 *
 * The "imprecise" variant only contains a value and optionally a parameter name.
 * The table is inferred from the context.
 */
function impreciseEmptySearchChangeRequest(ctx, answer) {
    const [base, param] = ctx.aux;
    // because we're imprecise, we're only valid if the agent asked a specific question
    if (base === null || param === null)
        return null;
    let answerFilter;
    if (answer instanceof thingtalk_1.Ast.Value)
        answerFilter = C.makeFilter(ctx.loader, param, '==', answer);
    else
        answerFilter = answer;
    if (answerFilter === null || !(answerFilter instanceof thingtalk_1.Ast.AtomBooleanExpression))
        return null;
    if (answerFilter.name !== param.name)
        return null;
    if (!C.checkFilter(base, answerFilter))
        return null;
    return emptySearchChangePhraseCommon(ctx, answerFilter);
}
exports.impreciseEmptySearchChangeRequest = impreciseEmptySearchChangeRequest;
//# sourceMappingURL=empty-search.js.map