"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.activate = activate;
const tslib_1 = require("tslib");
const coc_nvim_1 = require("coc.nvim");
const child_process_1 = require("child_process");
const os_1 = tslib_1.__importDefault(require("os"));
const tools_1 = require("./utils/tools");
const commands_1 = require("./commands");
const modify_tags_1 = require("./utils/modify-tags");
const config_1 = require("./utils/config");
const editor_1 = require("./editor");
const binaries_1 = require("./binaries");
const tests_1 = require("./utils/tests");
const playground_1 = require("./utils/playground");
const impl_1 = require("./utils/impl");
const lspcommands_1 = require("./utils/lspcommands");
const restartConfigs = [
    'go.goplsArgs',
    'go.goplsOptions',
    'go.goplsPath',
    'go.goplsUseDaemon',
];
async function activate(context) {
    (0, config_1.setStoragePath)(context.storagePath);
    if ((0, config_1.getConfig)().enable === false) {
        return;
    }
    registerGeneral(context);
    registerGopls(context);
    registerTest(context);
    registerTags(context);
    registerPlaygroud(context);
    registerGoImpl(context);
    registerTools(context);
    registerLspCommands(context);
}
async function registerGeneral(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.version", () => (0, commands_1.version)()));
}
async function registerGopls(context) {
    var _a;
    const config = (0, config_1.getConfig)();
    const command = await goplsPath(config.goplsPath);
    if (!command) {
        return;
    }
    const args = config.goplsArgs ? [...config.goplsArgs] : [];
    if (config.goplsUseDaemon !== false && !args.find(arg => arg.startsWith('-remote'))) {
        // Use daemon by default
        args.push('-remote=auto');
    }
    // TMPDIR needs to be resetted, because its altered by coc.nvim, which breaks
    // the automatic deamon launching of gopls.
    // See: https://github.com/neoclide/coc.nvim/commit/bdd9a9e1401fe6fdd57a9bd078e3651ecf1e0202
    const tmpdir = await coc_nvim_1.workspace.nvim.eval('$TMPDIR');
    const server = () => {
        return new Promise(resolve => {
            resolve((0, child_process_1.spawn)(command, args, {
                cwd: coc_nvim_1.workspace.cwd,
                env: Object.assign(Object.assign(Object.assign({}, process.env), { TMPDIR: tmpdir }), config.goplsEnv),
            }));
        });
    };
    const disabledFeatures = [
        ...((_a = config.disable.features) !== null && _a !== void 0 ? _a : []),
        config.disable.workspaceFolders && 'workspaceFolders',
        config.disable.diagnostics && 'diagnostics',
        config.disable.completion && 'completion',
    ].filter(Boolean);
    const clientOptions = {
        documentSelector: ['go', 'gomod', 'gowork'],
        initializationOptions: () => (0, config_1.getConfig)().goplsOptions,
        // TODO add once released: https://github.com/neoclide/coc.nvim/blob/79e9e048dfedbfc8b91330059fec5470f8b68f14/src/language-client/client.ts#L179
        // disableWorkspaceFolders: config.disable.workspaceFolders,
        // disableDiagnostics: config.disable.diagnostics,
        // disableCompletion: config.disable.completion,
        disableSnippetCompletion: config.disable.snippetCompletion,
        disabledFeatures,
    };
    const client = new coc_nvim_1.LanguageClient('go', 'gopls', server, clientOptions);
    if (config.checkForUpdates !== 'disabled' && !config.goplsPath) {
        await (0, commands_1.checkGopls)(client, config.checkForUpdates);
    }
    context.subscriptions.push(coc_nvim_1.services.registLanguageClient(client), 
    // restart gopls if options changed
    coc_nvim_1.workspace.onDidChangeConfiguration(async (e) => {
        if (restartConfigs.find(k => e.affectsConfiguration(k))) {
            await client.stop();
            client.restart();
        }
    }), coc_nvim_1.commands.registerCommand("go.install.gopls", () => (0, commands_1.installGopls)(client)));
}
async function goplsPath(goplsPath) {
    if (goplsPath) {
        if (goplsPath.startsWith('~')) {
            goplsPath = os_1.default.homedir() + goplsPath.slice(1);
        }
        if (!await (0, tools_1.commandExists)(goplsPath)) {
            coc_nvim_1.window.showMessage(`goplsPath is configured ("${goplsPath}"), but does not exist!`, 'error');
            return null;
        }
        return goplsPath;
    }
    if (!await (0, tools_1.installGoBin)(binaries_1.GOPLS)) {
        return;
    }
    return (0, tools_1.goBinPath)(binaries_1.GOPLS);
}
async function registerGoImpl(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.install.impl", () => (0, commands_1.installImpl)()), coc_nvim_1.commands.registerCommand("go.impl.cursor", async () => (0, impl_1.generateImplStubs)(await (0, editor_1.activeTextDocument)())));
}
async function registerTest(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.install.gotests", () => (0, commands_1.installGotests)()), coc_nvim_1.commands.registerCommand("go.test.generate.file", async () => (0, tests_1.generateTestsAll)(await (0, editor_1.activeTextDocument)())), coc_nvim_1.commands.registerCommand("go.test.generate.exported", async () => (0, tests_1.generateTestsExported)(await (0, editor_1.activeTextDocument)())), coc_nvim_1.commands.registerCommand("go.test.generate.function", async () => (0, tests_1.generateTestsFunction)(await (0, editor_1.activeTextDocument)())), coc_nvim_1.commands.registerCommand("go.test.toggle", async () => (0, tests_1.toogleTests)(await (0, editor_1.activeTextDocument)())));
}
async function registerTags(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.install.gomodifytags", () => (0, commands_1.installGomodifytags)()), coc_nvim_1.commands.registerCommand("go.tags.add", async (...tags) => (0, modify_tags_1.addTags)(await (0, editor_1.activeTextDocument)(), { tags })), coc_nvim_1.commands.registerCommand("go.tags.add.line", async (...tags) => (0, modify_tags_1.addTags)(await (0, editor_1.activeTextDocument)(), { tags, selection: "line" })), coc_nvim_1.commands.registerCommand("go.tags.add.prompt", async () => (0, modify_tags_1.addTags)(await (0, editor_1.activeTextDocument)(), { prompt: true })), coc_nvim_1.commands.registerCommand("go.tags.remove", async (...tags) => (0, modify_tags_1.removeTags)(await (0, editor_1.activeTextDocument)(), { tags })), coc_nvim_1.commands.registerCommand("go.tags.remove.line", async (...tags) => (0, modify_tags_1.removeTags)(await (0, editor_1.activeTextDocument)(), { tags, selection: "line" })), coc_nvim_1.commands.registerCommand("go.tags.remove.prompt", async () => (0, modify_tags_1.removeTags)(await (0, editor_1.activeTextDocument)(), { prompt: true })), coc_nvim_1.commands.registerCommand("go.tags.clear", async () => (0, modify_tags_1.clearTags)(await (0, editor_1.activeTextDocument)())), coc_nvim_1.commands.registerCommand("go.tags.clear.line", async () => (0, modify_tags_1.clearTags)(await (0, editor_1.activeTextDocument)(), { selection: "line" })));
}
async function registerPlaygroud(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.install.goplay", () => (0, commands_1.installGoplay)()), coc_nvim_1.commands.registerCommand("go.playground", async () => (0, playground_1.openPlayground)(await (0, editor_1.activeTextDocument)())));
}
async function registerTools(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.install.tools", () => (0, commands_1.installTools)()));
}
async function registerLspCommands(context) {
    context.subscriptions.push(coc_nvim_1.commands.registerCommand("go.gopls.tidy", lspcommands_1.goplsTidy));
}
//# sourceMappingURL=extension.js.map