var index = require('./index.js');
var React = require('react');
require('@grafarg/data');
require('react-dom');
require('@grafarg/e2e-selectors');
require('tty');
require('util');
require('os');
require('moment');
require('crypto');
require('jquery');
require('@grafana/aws-sdk');
var monaco = require('monaco-editor/esm/vs/editor/editor.api');
var ReactMonaco = require('react-monaco-editor');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var ReactMonaco__default = /*#__PURE__*/_interopDefaultLegacy(ReactMonaco);

/**
 * @internal -- only exported for tests
 */
function findInsertIndex(line) {
    for (let i = line.length - 1; i > 0; i--) {
        const ch = line.charAt(i);
        if (ch === '$') {
            return {
                index: i,
                prefix: line.substring(i),
            };
        }
        // Keep these seperators
        if (ch === ' ' || ch === '\t' || ch === '"' || ch === "'") {
            return {
                index: i + 1,
                prefix: line.substring(i + 1),
            };
        }
    }
    return {
        index: 0,
        prefix: line,
    };
}
function getCompletionItems(prefix, suggestions, range) {
    var _a;
    const items = [];
    for (const suggestion of suggestions) {
        if (prefix && !suggestion.label.startsWith(prefix)) {
            continue; // skip non-matching suggestions
        }
        items.push(Object.assign(Object.assign({}, suggestion), { kind: mapKinds(suggestion.kind), range, insertText: (_a = suggestion.insertText) !== null && _a !== void 0 ? _a : suggestion.label }));
    }
    return items;
}
function mapKinds(sug) {
    switch (sug) {
        case index.CodeEditorSuggestionItemKind.Method:
            return monaco.languages.CompletionItemKind.Method;
        case index.CodeEditorSuggestionItemKind.Field:
            return monaco.languages.CompletionItemKind.Field;
        case index.CodeEditorSuggestionItemKind.Property:
            return monaco.languages.CompletionItemKind.Property;
        case index.CodeEditorSuggestionItemKind.Constant:
            return monaco.languages.CompletionItemKind.Constant;
        case index.CodeEditorSuggestionItemKind.Text:
            return monaco.languages.CompletionItemKind.Text;
    }
    return monaco.languages.CompletionItemKind.Text;
}
/**
 * @alpha
 */
function registerSuggestions(language, getSuggestions) {
    if (!language || !getSuggestions) {
        return undefined;
    }
    return monaco.languages.registerCompletionItemProvider(language, {
        triggerCharacters: ['$'],
        provideCompletionItems: (model, position, context) => {
            const range = {
                startLineNumber: position.lineNumber,
                endLineNumber: position.lineNumber,
                startColumn: position.column,
                endColumn: position.column,
            };
            // Simple check if this was triggered by pressing `$`
            if (context.triggerCharacter === '$') {
                range.startColumn = position.column - 1;
                return {
                    suggestions: getCompletionItems('$', getSuggestions(), range),
                };
            }
            // Find the replacement region
            const currentLine = model.getValueInRange({
                startLineNumber: position.lineNumber,
                startColumn: 1,
                endLineNumber: position.lineNumber,
                endColumn: position.column,
            });
            const { index, prefix } = findInsertIndex(currentLine);
            range.startColumn = index + 1;
            const suggestions = getCompletionItems(prefix, getSuggestions(), range);
            if (suggestions.length) {
                // NOTE, this will replace any language provided suggestions
                return { suggestions };
            }
            // Default language suggestions
            return undefined;
        },
    });
}

class UnthemedCodeEditor extends React__default['default'].PureComponent {
    constructor() {
        super(...arguments);
        // This is replaced with a real function when the actual editor mounts
        this.getEditorValue = () => '';
        this.onBlur = () => {
            const { onBlur } = this.props;
            if (onBlur) {
                onBlur(this.getEditorValue());
            }
        };
        this.editorWillMount = (m) => {
            const { language, getSuggestions } = this.props;
            if (getSuggestions) {
                this.completionCancel = registerSuggestions(language, getSuggestions);
            }
        };
        this.editorDidMount = (editor) => {
            const { onSave, onEditorDidMount } = this.props;
            this.getEditorValue = () => editor.getValue();
            if (onSave) {
                editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, () => {
                    onSave(this.getEditorValue());
                });
            }
            if (onEditorDidMount) {
                onEditorDidMount(editor);
            }
        };
    }
    componentWillUnmount() {
        if (this.completionCancel) {
            this.completionCancel.dispose();
        }
    }
    componentDidUpdate(oldProps) {
        const { getSuggestions, language } = this.props;
        if (getSuggestions) {
            // Language changed
            if (language !== oldProps.language) {
                if (this.completionCancel) {
                    this.completionCancel.dispose();
                }
                this.completionCancel = registerSuggestions(language, getSuggestions);
            }
        }
    }
    render() {
        var _a;
        const { theme, language, width, height, showMiniMap, showLineNumbers, readOnly } = this.props;
        const value = (_a = this.props.value) !== null && _a !== void 0 ? _a : '';
        const longText = value.length > 100;
        const options = {
            wordWrap: 'off',
            codeLens: false,
            minimap: {
                enabled: longText && showMiniMap,
                renderCharacters: false,
            },
            readOnly,
            lineNumbersMinChars: 4,
            lineDecorationsWidth: 0,
            overviewRulerBorder: false,
            automaticLayout: true,
        };
        if (!showLineNumbers) {
            options.glyphMargin = false;
            options.folding = false;
            options.lineNumbers = 'off';
            options.lineDecorationsWidth = 5; // left margin when not showing line numbers
            options.lineNumbersMinChars = 0;
        }
        return (React__default['default'].createElement("div", { onBlur: this.onBlur },
            React__default['default'].createElement(ReactMonaco__default['default'], { width: width, height: height, language: language, theme: theme.isDark ? 'vs-dark' : 'vs-light', value: value, options: options, editorWillMount: this.editorWillMount, editorDidMount: this.editorDidMount })));
    }
}
var CodeEditor = index.withTheme(UnthemedCodeEditor);

exports.default = CodeEditor;
//# sourceMappingURL=CodeEditor.development.js.map
