"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.addParametersFromContext = exports.findChainParam = exports.isValidSearchQuestion = exports.isInfoPhraseCompatibleWithResult = exports.isFilterCompatibleWithResult = exports.isFilterCompatibleWithInfo = exports.isSimpleFilterExpression = exports.isSlotCompatibleWithResult = void 0;
const assert_1 = __importDefault(require("assert"));
const thingtalk_1 = require("thingtalk");
const C = __importStar(require("../ast_manip"));
const array_utils_1 = require("../array_utils");
const state_manip_1 = require("../state_manip");
function isFilterCompatibleWithInfo(info, filter) {
    assert_1.default(filter instanceof thingtalk_1.Ast.BooleanExpression);
    if (filter.isTrue || filter.isDontCare)
        return true;
    if (filter.isFalse)
        return false;
    if (filter instanceof thingtalk_1.Ast.OrBooleanExpression)
        return filter.operands.some((op) => isFilterCompatibleWithInfo(info, op));
    if (filter instanceof thingtalk_1.Ast.AndBooleanExpression)
        return filter.operands.every((op) => isFilterCompatibleWithInfo(info, op));
    if (filter instanceof thingtalk_1.Ast.NotBooleanExpression)
        return !isFilterCompatibleWithInfo(info, filter.expr);
    // approximate
    if (filter.isExternal || filter.isCompute)
        return true;
    assert_1.default(filter instanceof thingtalk_1.Ast.AtomBooleanExpression);
    const pname = filter.name;
    if (!info.has(pname))
        return false;
    if (!filter.value.isConstant())
        return true;
    switch (filter.operator) {
        case '==':
        case '=~':
            return filter.value.equals(info.get(pname));
        case 'contains':
        case 'contains~':
            return info.get(pname).value.some((v) => v.equals(filter.value));
        case 'in_array':
        case 'in_array~':
            return filter.value.value.some((v) => v.equals(info.get(pname)));
        case '>=':
            return info.get(pname).toJS() >= filter.value.toJS();
        case '<=':
            return info.get(pname).toJS() <= filter.value.toJS();
        default:
            // approximate
            return true;
    }
}
exports.isFilterCompatibleWithInfo = isFilterCompatibleWithInfo;
function isFilterCompatibleWithResult(topResult, filter) {
    if (filter.isTrue || filter.isDontCare)
        return true;
    if (filter.isFalse)
        return false;
    if (filter instanceof thingtalk_1.Ast.AndBooleanExpression)
        return filter.operands.every((op) => isFilterCompatibleWithResult(topResult, op));
    if (filter instanceof thingtalk_1.Ast.OrBooleanExpression)
        return filter.operands.some((op) => isFilterCompatibleWithResult(topResult, op));
    if (filter instanceof thingtalk_1.Ast.NotBooleanExpression)
        return !isFilterCompatibleWithResult(topResult, filter.expr);
    if (filter.isExternal) // approximate
        return true;
    if (filter.isCompute) // approximate
        return true;
    assert_1.default(filter instanceof thingtalk_1.Ast.AtomBooleanExpression);
    const values = topResult.value;
    // if the value was not returned, don't verbalize it
    if (!values[filter.name])
        return false;
    const resultValue = topResult.value[filter.name];
    if (resultValue instanceof thingtalk_1.Ast.EntityValue) {
        // approximate: all strings are made up so we don't need a true likeTest here
        if (filter.operator === '=~')
            return resultValue.display === filter.value.toJS();
        else
            return String(resultValue.toJS()) === String(filter.value.toJS());
    }
    switch (filter.operator) {
        case '==':
        case '=~':
            // approximate: all strings are made up so we don't need a true likeTest here
            return String(resultValue.toJS()) === String(filter.value.toJS());
        default:
            // approximate
            return true;
    }
}
exports.isFilterCompatibleWithResult = isFilterCompatibleWithResult;
function isSlotCompatibleWithResult(topResult, pname, infoValue) {
    const resultValue = topResult.value[pname];
    if (!resultValue)
        return false;
    if (resultValue instanceof thingtalk_1.Ast.ArrayValue && infoValue instanceof thingtalk_1.Ast.ArrayValue) {
        if (!array_utils_1.arraySubset(infoValue.value, resultValue.value))
            return false;
    }
    else {
        if (!resultValue.equals(infoValue))
            return false;
    }
    return true;
}
exports.isSlotCompatibleWithResult = isSlotCompatibleWithResult;
function isInfoPhraseCompatibleWithResult(topResult, info) {
    for (const [pname, infoValue] of info) {
        if (!isSlotCompatibleWithResult(topResult, pname, infoValue))
            return false;
    }
    return true;
}
exports.isInfoPhraseCompatibleWithResult = isInfoPhraseCompatibleWithResult;
/**
 * Check if asking a question on the parameters "questions" is allowed.
 *
 * This checks two things: that all parameters are valid output parameters of the table,
 * and all parameters are filterable.
 */
function isValidSearchQuestion(expr, questions) {
    for (const q of questions) {
        if (!C.isSameFunction(q.schema, expr.schema))
            return false;
        const arg = expr.schema.getArgument(q.name);
        if (!arg || arg.is_input)
            return false;
        if (arg.getAnnotation('filterable') === false)
            return false;
    }
    return true;
}
exports.isValidSearchQuestion = isValidSearchQuestion;
function addParametersFromContext(toInvocation, fromInvocation) {
    const newParams = new Set();
    for (const in_param of toInvocation.in_params) {
        if (in_param.value.isUndefined)
            continue;
        newParams.add(in_param.name);
    }
    let cloned = false;
    for (const in_param of fromInvocation.in_params) {
        if (in_param.value.isUndefined)
            continue;
        if (newParams.has(in_param.name))
            continue;
        if (!cloned) {
            toInvocation = toInvocation.clone();
            cloned = true;
        }
        state_manip_1.setOrAddInvocationParam(toInvocation, in_param.name, in_param.value);
    }
    return toInvocation;
}
exports.addParametersFromContext = addParametersFromContext;
function findChainParam(topResult, action) {
    const resultType = topResult.value.id.getType();
    let chainParam = undefined;
    for (const arg of action.schema.iterateArguments()) {
        if (arg.type.equals(resultType)) {
            chainParam = arg.name;
            break;
        }
    }
    return chainParam;
}
exports.findChainParam = findChainParam;
function isSimpleFilterExpression(table) {
    return table instanceof thingtalk_1.Ast.FilterExpression && table.expression instanceof thingtalk_1.Ast.InvocationExpression;
}
exports.isSimpleFilterExpression = isSimpleFilterExpression;
//# sourceMappingURL=common.js.map