<commit_before>/**
 * Based on https://github.com/Microsoft/vscode/blob/master/extensions/json/server/src/jsonCompletion.ts
 *
 * But with our types etc.
 *
 * I deleted stuff around `jsonContributions` (I have no idea what it is)
 */

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import Parser = require('../jsonParser');
import SchemaService = require('./jsonSchemaService');
import JsonSchema = require('../jsonSchema');
import {localize} from "../localize";
type Thenable<T> = Promise<T>;

/**
 * Register our schemas
 * Mostly downloaded from http://json.schemastore.org/
 */
const schemas: { fileName: string, content: JsonSchema.IJSONSchema }[] = [
    {
        fileName: 'tsconfig.json',
        content: require('./schemas/tsconfig.json')
    }
];
schemas.forEach(config => {
    SchemaService.resolveSchemaContent(config.content);
});


/**
 * BAS: My functions
 */
import {Types}  from "../../../../../socket/socketContract";
import * as utils from "../../../../../common/utils";
import * as fmc from "../../../../disk/fileModelCache";
export function getCompletionsAtPosition(this:{}, query: Types.GetCompletionsAtPositionQuery): Promise<Types.GetCompletionsAtPositionResponse> {
    const {filePath, prefix} = query;
    const offset = query.position;
    const completionsToReturn: Types.Completion[] = [];
    const endsInPunctuation = utils.prefixEndsInPunctuation(prefix);
    const schema = schemas[0].content;

    const contents = fmc.getOrCreateOpenFile(filePath).getContents();
    const doc = Parser.parse(contents);

    const result = utils.resolve({
        completions: completionsToReturn,
        endsInPunctuation: endsInPunctuation
    });

    // TODO: validation :)
    if (!doc.errors.length) {
        doc.validate(schema);
        // console.log('Schema Validation:',doc.errors,doc.warnings);
    }
    else {
        // console.log('Parse Errors:', doc.errors);
    }

    // TODO: autocomplete :)
    let node = doc.getNodeFromOffsetEndInclusive(offset);

    /**
     * Collects suggestions
     */
    let proposed: { [key: string]: boolean } = {};
    let collector: ISuggestionsCollector = {
        add: (suggestion: CompletionItem) => {
            if (!proposed[suggestion.label]) {
                proposed[suggestion.label] = true;

                if (!suggestion.insertText) {
                    // I don't think this is ever triggered, but to be safe
                    completionsToReturn.push({
                        kind: ts.ScriptElementKind.unknown,
                        name: `"${suggestion.label}"`,
                        display: '',
                        comment: suggestion.documentation
                    });
                }
                else {
                    let template = suggestion.insertText;
                    /** Replace `{{}}` with `${}` */
                    template = template.replace(/\{\{/g,"${");
                    template = template.replace(/\}\}/g,"}");

                    completionsToReturn.push({
                        kind: "snippet",
                        snippet: {
                            name: suggestion.label,<commit_msg>better completions<commit_after>/**
 * Based on https://github.com/Microsoft/vscode/blob/master/extensions/json/server/src/jsonCompletion.ts
 *
 * But with our types etc.
 *
 * I deleted stuff around `jsonContributions` (I have no idea what it is)
 */

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import Parser = require('../jsonParser');
import SchemaService = require('./jsonSchemaService');
import JsonSchema = require('../jsonSchema');
import {localize} from "../localize";
type Thenable<T> = Promise<T>;

/**
 * Register our schemas
 * Mostly downloaded from http://json.schemastore.org/
 */
const schemas: { fileName: string, content: JsonSchema.IJSONSchema }[] = [
    {
        fileName: 'tsconfig.json',
        content: require('./schemas/tsconfig.json')
    }
];
schemas.forEach(config => {
    SchemaService.resolveSchemaContent(config.content);
});


/**
 * BAS: My functions
 */
import {Types}  from "../../../../../socket/socketContract";
import * as utils from "../../../../../common/utils";
import * as fmc from "../../../../disk/fileModelCache";
export function getCompletionsAtPosition(this:{}, query: Types.GetCompletionsAtPositionQuery): Promise<Types.GetCompletionsAtPositionResponse> {
    const {filePath, prefix} = query;
    const offset = query.position;
    const completionsToReturn: Types.Completion[] = [];
    const endsInPunctuation = utils.prefixEndsInPunctuation(prefix);
    const schema = schemas[0].content;

    const contents = fmc.getOrCreateOpenFile(filePath).getContents();
    const doc = Parser.parse(contents);

    const result = utils.resolve({
        completions: completionsToReturn,
        endsInPunctuation: endsInPunctuation
    });

    // TODO: validation :)
    if (!doc.errors.length) {
        doc.validate(schema);
        // console.log('Schema Validation:',doc.errors,doc.warnings);
    }
    else {
        // console.log('Parse Errors:', doc.errors);
    }

    // TODO: autocomplete :)
    let node = doc.getNodeFromOffsetEndInclusive(offset);

    /**
     * Collects suggestions
     */
    let proposed: { [key: string]: boolean } = {};
    let collector: ISuggestionsCollector = {
        add: (suggestion: CompletionItem) => {
            if (!proposed[suggestion.label]) {
                proposed[suggestion.label] = true;

                if (
                    (!suggestion.insertText || !suggestion.insertText.match(/\{\{/g))) {
                    let kind = ts.ScriptElementKind.unknown;
                    switch (suggestion.kind) {
                        case CompletionItemKind.Snippet:
                            kind = ts.ScriptElementKind.unknown;
                            break;
                        case CompletionItemKind.Text:
                            kind = ts.ScriptElementKind.unknown;
                            break;
                        case CompletionItemKind.Module:
                            kind = ts.ScriptElementKind.moduleElement;
                            break;
                        case CompletionItemKind.Property:
                            kind = ts.ScriptElementKind.memberVariableElement;
                            break;
                        case CompletionItemKind.Value:
                            kind = ts.ScriptElementKind.memberVariableElement;
                            break;
                    }
                    completionsToReturn.push({
                        kind,
                        name: `${suggestion.label}`,
                        display: '',
                        comment: suggestion.documentation
                    });
                }
                else {
                    let template = suggestion.insertText;
                    /** Replace `{{}}` with `${}` */
                    template = template.replace(/\{\{/g,"${");
                    template = template.replace(/\}\}/g,"}");

                    completionsToReturn.push({
                        kind: "snippet",
                        snippet: {
                            name: suggestion.label,
{'fraction_non_alphanumeric': 0.17106437221159976, 'fraction_numerical': 0.00025493945188017844, 'mean_word_length': 1.6650815217391304, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3867627', 'n_tokens_mistral': 1965, 'n_tokens_neox': 1897, 'n_words': 421}