"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.booleanQuestion = exports.corefConstant = exports.listProposalSearchQuestionReply = exports.learnMoreSearchQuestionReply = exports.displayResultSearchQuestionReply = exports.recommendationSearchQuestionReply = exports.userSearchQuestionForListKeyFn = 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");
function userSearchQuestionForListKeyFn([name, questions]) {
    if (questions.length === 0)
        return { idType: null, functionName: null };
    return {
        idType: name ? name.getType() : null,
        functionName: questions[0].schema.qualifiedName
    };
}
exports.userSearchQuestionForListKeyFn = userSearchQuestionForListKeyFn;
function areQuestionsValidForContext(ctx, questions) {
    if (ctx.resultInfo.isAggregation)
        return null;
    const schema = ctx.currentFunction;
    // if the function only contains one parameter, do not generate projection for it
    if (Object.keys(schema.out).length === 1)
        return null;
    for (const q of questions) {
        if (!C.isSameFunction(schema, q.schema))
            return false;
        const arg = schema.getArgument(q.name);
        if (!arg || arg.is_input)
            return false;
    }
    return true;
}
function recommendationSearchQuestionReply(ctx, questions) {
    const proposal = ctx.aux;
    const { topResult, info, } = proposal;
    if (!topResult.value.id)
        return null;
    if (info !== null) {
        for (const q of questions) {
            if (info.has(q.name))
                return null;
        }
    }
    if (!areQuestionsValidForContext(ctx, questions))
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    const newFilter = new thingtalk_1.Ast.BooleanExpression.Atom(null, 'id', '==', topResult.value.id);
    const newTable = refinement_helpers_1.queryRefinement(currentTable, newFilter, refinement_helpers_1.refineFilterToAnswerQuestion, questions.map((q) => q.name));
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.recommendationSearchQuestionReply = recommendationSearchQuestionReply;
function learnMoreSearchQuestionReply(ctx, questions) {
    const topResult = ctx.results[0];
    if (!areQuestionsValidForContext(ctx, questions))
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    if (!topResult.value.id)
        return null;
    const newFilter = new thingtalk_1.Ast.BooleanExpression.Atom(null, 'id', '==', topResult.value.id);
    const newTable = refinement_helpers_1.queryRefinement(currentTable, newFilter, refinement_helpers_1.refineFilterToAnswerQuestion, questions.map((q) => q.name));
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.learnMoreSearchQuestionReply = learnMoreSearchQuestionReply;
function displayResultSearchQuestionReply(ctx, questions) {
    if (!areQuestionsValidForContext(ctx, questions))
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    const newTable = refinement_helpers_1.queryRefinement(currentTable, null, refinement_helpers_1.refineFilterToAnswerQuestion, questions.map((q) => q.name));
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.displayResultSearchQuestionReply = displayResultSearchQuestionReply;
function listProposalSearchQuestionReply(ctx, [name, questions]) {
    const proposal = ctx.aux;
    const [results, info] = proposal;
    if (name !== null) {
        let good = false;
        for (const result of results) {
            if (!result.value.id)
                continue;
            if (result.value.id.equals(name)) {
                good = true;
                break;
            }
        }
        if (!good)
            return null;
    }
    if (info !== null) {
        for (const q of questions) {
            if (info.has(q.name))
                return null;
        }
    }
    if (!areQuestionsValidForContext(ctx, questions))
        return null;
    const currentStmt = ctx.current.stmt;
    const currentTable = currentStmt.expression;
    let newTable;
    if (name !== null) {
        const newFilter = new thingtalk_1.Ast.BooleanExpression.Atom(null, 'id', '==', name);
        newTable = refinement_helpers_1.queryRefinement(currentTable, newFilter, refinement_helpers_1.refineFilterToAnswerQuestion, questions.map((q) => q.name));
    }
    else {
        newTable = refinement_helpers_1.queryRefinement(currentTable, null, null, questions.map((q) => q.name));
    }
    if (newTable === null)
        return null;
    return state_manip_1.addQuery(ctx, 'execute', newTable, 'accepted');
}
exports.listProposalSearchQuestionReply = listProposalSearchQuestionReply;
function corefConstant(ctx, base, param) {
    const previous = ctx.previousDomain;
    assert_1.default(previous);
    if (!previous.results || previous.results.results.length === 0)
        return null;
    const ctxStmt = previous.stmt;
    const ctxSchema = ctxStmt.expression.schema;
    if (!ctxSchema.class) // FIXME not sure how this happens...
        return null;
    if (ctxSchema.class.name !== base.schema.class.name)
        return null;
    if (!C.isSameFunction(ctxSchema, param.schema))
        return null;
    const result = previous.results.results[0];
    if (!result.value[param.name])
        return null;
    return result.value[param.name];
}
exports.corefConstant = corefConstant;
function booleanQuestion(base, slot) {
    var _a, _b;
    if (base !== null) {
        if (!C.isSameFunction(base.schema, slot.schema))
            return null;
    }
    const ast = slot.ast;
    if (!(ast instanceof thingtalk_1.Ast.AtomBooleanExpression)) {
        assert_1.default(ast instanceof thingtalk_1.Ast.AndBooleanExpression);
        assert_1.default(ast.operands.length === 2);
        const [op1, op2] = [ast.operands[0], ast.operands[1]];
        assert_1.default(op1 instanceof thingtalk_1.Ast.AtomBooleanExpression);
        assert_1.default(op2 instanceof thingtalk_1.Ast.AtomBooleanExpression);
        assert_1.default(op1.name === op2.name);
        return [{
                schema: slot.schema,
                type: slot.ptype,
                filterable: (_a = slot.schema.getArgument(op1.name).getImplementationAnnotation('filterable')) !== null && _a !== void 0 ? _a : true,
                name: op1.name,
                ast: new thingtalk_1.Ast.Value.VarRef(op1.name)
            }];
    }
    if (ast.name === 'id')
        return null;
    return [{
            schema: slot.schema,
            type: slot.ptype,
            filterable: (_b = slot.schema.getArgument(ast.name).getImplementationAnnotation('filterable')) !== null && _b !== void 0 ? _b : true,
            name: ast.name,
            ast: new thingtalk_1.Ast.Value.VarRef(ast.name),
        }];
}
exports.booleanQuestion = booleanQuestion;
//# sourceMappingURL=coref-questions.js.map