"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.impreciseSearchQuestionAnswer = exports.preciseSearchQuestionAnswer = exports.makeSearchQuestion = exports.checkFilterPairForDisjunctiveQuestion = exports.checkFilterPairForDisjunctiveQuestionWithConstant = exports.preciseSearchQuestionAnswerKeyFn = 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 refinement_helpers_1 = require("./refinement-helpers");
const common_1 = require("./common");
function preciseSearchQuestionAnswerKeyFn([table, action, hasYes]) {
    return {
        functionName: table.schema.qualifiedName,
        actionFunctionName: action ? action.schema.qualifiedName : null
    };
}
exports.preciseSearchQuestionAnswerKeyFn = preciseSearchQuestionAnswerKeyFn;
function isGoodSearchQuestion(ctx, questions) {
    const currentStmt = ctx.current.stmt;
    if (!common_1.isValidSearchQuestion(currentStmt.lastQuery, questions))
        return false;
    const ctxFilterTable = C.findFilterExpression(currentStmt.expression);
    if (!ctxFilterTable)
        return false;
    for (const q of questions) {
        if (C.filterUsesParam(ctxFilterTable.filter, q.name))
            return false;
    }
    return true;
}
function checkFilterPairForDisjunctiveQuestion(ctx, f1, f2) {
    var _a;
    if (!(f1.ast instanceof thingtalk_1.Ast.AtomBooleanExpression))
        return null;
    if (!(f2.ast instanceof thingtalk_1.Ast.AtomBooleanExpression))
        return null;
    if (!ctx.currentFunction.is_list)
        return null;
    if (!C.isSameFunction(ctx.currentFunction, f1.schema))
        return null;
    if (!C.isSameFunction(f1.schema, f2.schema))
        return null;
    if (f1.ast.name !== f2.ast.name)
        return null;
    if (!f1.ast.value.getType().equals(f2.ast.value.getType()))
        return null;
    if (f1.ast.value.equals(f2.ast.value))
        return null;
    const filterable = (_a = f1.schema.getArgument(f1.ast.name)
        .getImplementationAnnotation('filterable')) !== null && _a !== void 0 ? _a : true;
    if (!filterable)
        return null;
    let good1 = false;
    let good2 = false;
    for (const result of ctx.results) {
        const value = result.value[f1.ast.name];
        if (!value)
            return null;
        if (value.equals(f1.ast.value))
            good1 = true;
        if (value.equals(f2.ast.value))
            good2 = true;
        if (good1 && good2)
            break;
    }
    if (!good1 || !good2)
        return null;
    return { schema: f1.schema, type: f1.ptype, name: f1.ast.name,
        filterable, ast: new thingtalk_1.Ast.Value.VarRef(f1.ast.name) };
}
exports.checkFilterPairForDisjunctiveQuestion = checkFilterPairForDisjunctiveQuestion;
function checkFilterPairForDisjunctiveQuestionWithConstant(ctx, f1, c) {
    var _a;
    if (!(f1.ast instanceof thingtalk_1.Ast.AtomBooleanExpression))
        return null;
    const filterable = (_a = f1.schema.getArgument(f1.ast.name)
        .getImplementationAnnotation('filterable')) !== null && _a !== void 0 ? _a : true;
    const pslot = { schema: f1.schema, name: f1.ast.name, type: f1.ptype, filterable,
        ast: new thingtalk_1.Ast.Value.VarRef(f1.ast.name) };
    const f2 = C.makeFilter(ctx.loader, pslot, f1.ast.operator, c);
    if (!f2)
        return null;
    return checkFilterPairForDisjunctiveQuestion(ctx, f1, f2);
}
exports.checkFilterPairForDisjunctiveQuestionWithConstant = checkFilterPairForDisjunctiveQuestionWithConstant;
function makeSearchQuestion(ctx, questions) {
    if (!isGoodSearchQuestion(ctx, questions))
        return null;
    if (questions.length === 0)
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_generic_search_question', null));
    if (questions.length === 1) {
        const currentStmt = ctx.current.stmt;
        const type = currentStmt.lastQuery.schema.getArgument(questions[0].name).type;
        return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_search_question', questions.map((q) => q.name)), null, type);
    }
    return state_manip_1.makeAgentReply(ctx, state_manip_1.makeSimpleState(ctx, 'sys_search_question', questions.map((q) => q.name)));
}
exports.makeSearchQuestion = makeSearchQuestion;
class AnswersQuestionVisitor extends thingtalk_1.Ast.NodeVisitor {
    constructor(questions) {
        super();
        this.questions = questions;
        this.answersQuestion = false;
    }
    visitAtomBooleanExpression(atom) {
        if (this.questions.some((q) => q === atom.name))
            this.answersQuestion = true;
        return true;
    }
    visitDontCareBooleanExpression(atom) {
        if (this.questions.some((q) => q === atom.name))
            this.answersQuestion = true;
        return true;
    }
}
/**
 * Check if the table filters on the parameters `questions` (effectively providing a constraint on question)
 */
function isQueryAnswerValidForQuestion(table, questions) {
    assert_1.default(Array.isArray(questions));
    const visitor = new AnswersQuestionVisitor(questions);
    table.visit(visitor);
    return visitor.answersQuestion;
}
function preciseSearchQuestionAnswer(ctx, [answerTable, answerAction, _bool]) {
    const questions = ctx.state.dialogueActParam;
    if (questions !== null && !isQueryAnswerValidForQuestion(answerTable, questions))
        return null;
    if (!(answerTable instanceof thingtalk_1.Ast.FilterExpression))
        return null;
    if (!C.isSameFunction(answerTable.schema, ctx.currentFunction))
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    // TODO we need to push down the filter, if possible
    if (!common_1.isSimpleFilterExpression(answerTable))
        return null;
    if (answerAction !== null) {
        assert_1.default(answerAction instanceof thingtalk_1.Ast.Invocation);
        if (ctx.nextFunction !== null) {
            if (!C.isSameFunction(answerAction.schema, ctx.nextFunction))
                return null;
            // check that we don't fill the chain parameter through this path:
            // the chain parameter can only be filled if the agent shows the results
            for (const in_param of answerAction.in_params) {
                if (in_param.name === ctx.nextInfo.chainParameter &&
                    !ctx.nextInfo.chainParameterFilled)
                    return null;
            }
            answerAction = common_1.addParametersFromContext(answerAction, C.getInvocation(ctx.next));
        }
    }
    const newTable = refinement_helpers_1.queryRefinement(currentTable, answerTable.filter, refinement_helpers_1.refineFilterToAnswerQuestion, null);
    if (newTable === null)
        return null;
    if (answerAction !== null)
        return state_manip_1.addQueryAndAction(ctx, 'execute', newTable, answerAction, 'accepted');
    else
        return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.preciseSearchQuestionAnswer = preciseSearchQuestionAnswer;
function impreciseSearchQuestionAnswer(ctx, answer) {
    var _a;
    const questions = ctx.state.dialogueActParam;
    if (questions === null || questions.length !== 1)
        return null;
    assert_1.default(Array.isArray(questions) && questions.length > 0);
    let answerFilter;
    if (answer === 'dontcare') {
        answerFilter = {
            schema: ctx.currentFunction,
            ptype: ctx.currentFunction.getArgType(questions[0]),
            ast: new thingtalk_1.Ast.BooleanExpression.DontCare(null, questions[0])
        };
    }
    else if (answer instanceof thingtalk_1.Ast.Value) {
        assert_1.default(questions.length === 1);
        assert_1.default(answer instanceof thingtalk_1.Ast.Value);
        const arg = ctx.currentFunction.getArgument(questions[0]);
        const pslot = { schema: ctx.currentFunction, type: arg.type, filterable: (_a = arg.getImplementationAnnotation('filterable')) !== null && _a !== void 0 ? _a : true, name: questions[0],
            ast: new thingtalk_1.Ast.Value.VarRef(questions[0]) };
        const newFilter = C.makeFilter(ctx.loader, pslot, '==', answer);
        if (newFilter === null)
            return null;
        answerFilter = newFilter;
    }
    else {
        answerFilter = answer;
        let pname;
        if (answer.ast instanceof thingtalk_1.Ast.AndBooleanExpression) {
            assert_1.default(answer.ast.operands.length === 2);
            const [op1, op2] = answer.ast.operands;
            assert_1.default(op1 instanceof thingtalk_1.Ast.AtomBooleanExpression
                && op2 instanceof thingtalk_1.Ast.AtomBooleanExpression);
            assert_1.default(op1.name === op2.name &&
                op1.value.getType().equals(op2.value.getType()));
            pname = op1.name;
        }
        else if (answer.ast instanceof thingtalk_1.Ast.NotBooleanExpression) {
            const inner = answer.ast.expr;
            assert_1.default(inner instanceof thingtalk_1.Ast.AtomBooleanExpression ||
                inner instanceof thingtalk_1.Ast.DontCareBooleanExpression);
            pname = inner.name;
        }
        else {
            assert_1.default(answer.ast instanceof thingtalk_1.Ast.AtomBooleanExpression ||
                answer.ast instanceof thingtalk_1.Ast.DontCareBooleanExpression);
            pname = answer.ast.name;
        }
        if (!questions.some((q) => q === pname))
            return null;
    }
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    if (!C.checkFilter(currentTable, answerFilter))
        return null;
    const newTable = refinement_helpers_1.queryRefinement(currentTable, answerFilter.ast, refinement_helpers_1.refineFilterToAnswerQuestion, null);
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.impreciseSearchQuestionAnswer = impreciseSearchQuestionAnswer;
//# sourceMappingURL=search-questions.js.map