"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.addSlotToResultPhrase = exports.addSlotToBag = exports.makeResultPhrase = exports.mergeResultPhrase = exports.resultPhraseKeyFn = 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 common_1 = require("./common");
const MAX_RESULTS = 3;
function resultPhraseKeyFn(phrase) {
    return {
        functionName: phrase.ctx.currentFunction.qualifiedName
    };
}
exports.resultPhraseKeyFn = resultPhraseKeyFn;
function mergeResultPhrase(p1, p2) {
    assert_1.default(p1.ctx === p2.ctx);
    // check that both are compatible with some result, by intersecting
    // the compatible arrays
    const compatible = [];
    for (const resultIdx of p1.compatible) {
        if (p2.compatible.includes(resultIdx))
            compatible.push(resultIdx);
    }
    if (compatible.length === 0)
        return null;
    // this will also check that they don't both say the same thing
    const merged = slot_bag_1.SlotBag.merge(p1.info, p2.info);
    if (!merged)
        return null;
    return { ctx: p1.ctx, info: merged, compatible };
}
exports.mergeResultPhrase = mergeResultPhrase;
function makeResultPhrase(ctx, info) {
    if (info.schema !== null) {
        if (!C.isSameFunction(ctx.currentFunction, info.schema))
            return null;
    }
    // check that the filter is compatible with at least one of the top 3 results
    const results = ctx.results;
    const compatible = [];
    for (let i = 0; i < Math.min(MAX_RESULTS, results.length); i++) {
        if (common_1.isInfoPhraseCompatibleWithResult(results[i], info)) {
            compatible.push(i);
            break;
        }
    }
    if (compatible.length === 0)
        return null;
    if (info.schema !== null)
        return { ctx, info, compatible };
    const clone = info.clone();
    clone.schema = ctx.currentFunction;
    return { ctx, info: clone, compatible };
}
exports.makeResultPhrase = makeResultPhrase;
function addSlotToBagCloned(bag, filter) {
    if (filter instanceof thingtalk_1.Ast.AndBooleanExpression) {
        // we treat "serves Italian and Chinese" the same as "serves Italian or Chinese"
        let newBag = bag;
        const newSlots = [];
        for (const operand of filter.operands) {
            const added = addSlotToBagCloned(newBag, operand);
            if (!added)
                return null;
            newBag = added[0];
            newSlots.push(...added[1]);
        }
        return [newBag, newSlots];
    }
    if (!(filter instanceof thingtalk_1.Ast.AtomBooleanExpression))
        return null;
    const arg = bag.schema.getArgument(filter.name);
    if (!arg || arg.is_input)
        return null;
    const ptype = arg.type;
    const vtype = filter.value.getType();
    if (filter.operator === 'contains' || filter.operator === 'contains~') {
        if (!ptype.equals(new thingtalk_1.Type.Array(vtype)))
            return null;
        const existing = bag.get(filter.name);
        if (existing) {
            assert_1.default(existing instanceof thingtalk_1.Ast.ArrayValue);
            if (existing.value.some((v) => v.equals(filter.value)))
                return null;
            existing.value.push(filter.value);
        }
        else {
            bag.set(filter.name, new thingtalk_1.Ast.Value.Array([filter.value]));
        }
        return [bag, [filter.name]];
    }
    else {
        if (filter.operator !== '==' && filter.operator !== '=~')
            return null;
        if (!ptype.equals(vtype))
            return null;
        if (bag.has(filter.name))
            return null;
        bag.set(filter.name, filter.value);
        return [bag, [filter.name]];
    }
}
function addSlotToBag(bag, filter) {
    const schema = bag.schema;
    if (!C.isSameFunction(schema, filter.schema))
        return null;
    let name;
    if (filter.ast instanceof thingtalk_1.Ast.AndBooleanExpression) {
        const atom = filter.ast.operands[0];
        if (!(atom instanceof thingtalk_1.Ast.AtomBooleanExpression))
            return null;
        name = atom.name;
    }
    else {
        if (!(filter.ast instanceof thingtalk_1.Ast.AtomBooleanExpression))
            return null;
        name = filter.ast.name;
    }
    if (bag.has(name))
        return null;
    const clone = bag.clone();
    return addSlotToBagCloned(clone, filter.ast);
}
exports.addSlotToBag = addSlotToBag;
function addSlotToResultPhrase(phrase, filter) {
    const added = addSlotToBag(phrase.info, filter);
    if (!added)
        return null;
    const [newBag, newSlots] = added;
    const compatible = [];
    const results = phrase.ctx.results;
    for (const resultIdx of phrase.compatible) {
        const result = results[resultIdx];
        let good = true;
        for (const newSlot of newSlots) {
            if (!common_1.isSlotCompatibleWithResult(result, newSlot, newBag.get(newSlot))) {
                good = false;
                break;
            }
        }
        if (good)
            compatible.push(resultIdx);
    }
    if (compatible.length === 0)
        return null;
    return { ctx: phrase.ctx, info: newBag, compatible };
}
exports.addSlotToResultPhrase = addSlotToResultPhrase;
//# sourceMappingURL=results.js.map