"use strict";
// -*- mode: typescript; indent-tabs-mode: nil; js-basic-offset: 4 -*-
//
// This file is part of Genie
//
// Copyright 2019-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: Silei Xu <silei@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 });
const thingtalk_1 = require("thingtalk");
const random_1 = require("../../utils/random");
const misc_utils_1 = require("../../utils/misc-utils");
const I18n = __importStar(require("../../i18n"));
function getEntityType(type) {
    if (type instanceof thingtalk_1.Type.Entity)
        return type.type;
    if (type instanceof thingtalk_1.Type.Array)
        return getEntityType(type.elem);
    return null;
}
function isString(type) {
    if (type.isString)
        return true;
    if (type instanceof thingtalk_1.Type.Array)
        return isString(type.elem);
    return false;
}
class ConstantSampler {
    constructor(schemaRetriever, constProvider, options) {
        this._schemaRetriever = schemaRetriever;
        this._constProvider = constProvider;
        this._options = options;
        this._langPack = I18n.get(options.locale);
        this._cachedStrings = {};
        this._cachedEntities = {};
    }
    _sampleEntities(data) {
        const sampled = random_1.choose(data.filter((entity) => entity.name.length < 25), this._options.sample_size, this._options.rng);
        return sampled.filter((entity) => /^[a-zA-Z0-9 .]*$/.test(entity.name)).map((entity) => {
            return {
                value: entity.value,
                display: entity.name
            };
        });
    }
    _sampleStrings(data) {
        const rng = this._options.rng;
        const langPack = this._langPack;
        const sampleOne = function (string) {
            let attempts = 1000;
            while (attempts > 0) {
                const sampled = misc_utils_1.sampleString(string.value.split(' '), langPack, rng);
                if (sampled)
                    return sampled;
                attempts -= 1;
            }
            return null;
        };
        const sampled = random_1.choose(data.map(sampleOne).filter(Boolean), this._options.sample_size, rng);
        return sampled.filter((string) => /^[a-zA-Z0-9 .]*$/.test(string));
    }
    async _retrieveStringSamples(name) {
        if (name in this._cachedStrings)
            return this._cachedStrings[name];
        const data = await this._constProvider.get('string', name);
        if (data.length === 0)
            return [];
        const sampled = this._sampleStrings(data);
        this._cachedStrings[name] = sampled;
        return sampled;
    }
    async _retrieveEntitySamples(name) {
        if (name in this._cachedEntities)
            return this._cachedEntities[name];
        const data = await this._constProvider.getEntity(name);
        if (data.length === 0)
            return [];
        const sampled = this._sampleEntities(data);
        this._cachedEntities[name] = sampled;
        return sampled;
    }
    async _sampleOneDevice(device) {
        const deviceClass = await this._schemaRetriever.getFullSchema(device);
        const functions = Object.assign({}, deviceClass.queries, deviceClass.actions);
        const constants = [];
        for (const f in functions) {
            const functionDef = functions[f];
            for (const argument of functionDef.iterateArguments()) {
                const arg = argument.name;
                const string_values = argument.getImplementationAnnotation('string_values');
                const entityType = getEntityType(argument.type);
                if (string_values) {
                    let samples = await this._retrieveStringSamples(`org.schema:${f}_${arg}`);
                    if (samples.length === 0)
                        samples = await this._retrieveStringSamples(string_values);
                    if (entityType) {
                        if (['tt:hashtag', 'tt:username'].includes(entityType)) {
                            samples.forEach((sample) => {
                                constants.push([`param:@${device}.${f}:${arg}:Entity(${entityType})`, sample]);
                            });
                        }
                        else {
                            samples.forEach((sample) => {
                                constants.push([`param:@${device}.${f}:${arg}:Entity(${entityType})`, `null`, sample]);
                            });
                        }
                        if (arg === 'id') {
                            samples.forEach((sample) => {
                                constants.push([`param:@${device}.${f}:${arg}:String`, sample]);
                            });
                        }
                    }
                    else if (isString(argument.type)) {
                        samples.forEach((sample) => {
                            constants.push([`param:@${device}.${f}:${arg}:String`, sample]);
                        });
                    }
                }
                else if (entityType) {
                    const samples = await this._retrieveEntitySamples(entityType);
                    samples.forEach((sample) => {
                        constants.push([
                            `param:@${device}.${f}:${arg}:Entity(${entityType})`,
                            sample.value,
                            sample.display
                        ]);
                    });
                    if (arg === 'id') {
                        samples.forEach((sample) => {
                            constants.push([`param:@${device}.${f}:${arg}:String`, sample.display]);
                        });
                    }
                }
            }
        }
        return constants;
    }
    async sample() {
        const samples = [];
        for (const device of this._options.devices.split(',')) {
            for (const sample of await this._sampleOneDevice(device))
                samples.push(sample);
        }
        return samples;
    }
}
exports.default = ConstantSampler;
//# sourceMappingURL=constants-sampler.js.map