import * as monaco from 'monaco-editor';

const commands = [
    { name: 'set_global', displayName: 'Set Global Variable', text: 'globals["key"] = "value";\n' },
    { name: 'get_global', displayName: 'Get Global Variable', text: 'const value = globals["key"];\n' },
    { name: 'set_variable', displayName: 'Set Variable', text: 'variables["key"] = "value";\n' },
    { name: 'get_variable', displayName: 'Get Variable', text: 'const value = variables["key"];\n' },
    { name: 'get_response_body', displayName: 'Get Response Body', text: 'const body = response.body;\n' },
    { name: 'parse_response_body', displayName: 'Parse Response Body', text: 'JSON.parse(response.body);\n' },
    { name: 'get_response_headers', displayName: 'Get Response Header', text: 'const header_value = response.headers["header-key"];\n' }
];

class VariableSnippet {
    constructor(options = {}) {
        this.commands = commands || []; // Array of command objects
    }

    init(element, editor) {
        this.editor = editor; // Store the editor reference
        this.render(element);
    }

    render(element) {
        const commandsList = this.commands.map(command => {
            return `<button class="btn btn-link command-button" data-command="${command.name}">${command.displayName}</button>`;
        }).join('');

        element.innerHTML = `<div class="commands-list">${commandsList}</div>`;

        // Attach event listeners
        element.querySelectorAll('.command-button').forEach(button => {
            button.addEventListener('click', (event) => {
                const commandName = event.target.getAttribute('data-command');
                const command = this.commands.find(cmd => cmd.name === commandName);

                if (command && this.editor) {
                    this.appendTextToEditor(command.text);
                }
            });
        });
    }

    appendTextToEditor(text) {
        const model = this.editor.getModel();
        const position = this.editor.getPosition();
        this.editor.executeEdits('', [{
            range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column),
            text: text,
            forceMoveMarkers: true
        }]);
        this.editor.focus();
    }
}
export default VariableSnippet;

// Usage:
//const snippet = new VariableSnippet();
//snippet.init(document.getElementById('snippet-container'), editor);


