"use strict";
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;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommonLspService = void 0;
const fs_1 = __importDefault(require("fs"));
const path = __importStar(require("path"));
const url_1 = require("url");
const lsp = __importStar(require("vscode-languageserver-protocol/node"));
const winston_1 = __importDefault(require("winston"));
const util_1 = require("../../../util/util");
class CommonLspService {
    constructor(lspServerBin, workspace) {
        this.isStarted = false;
        this.lspServerBin = (0, util_1.resolveFilePath)(lspServerBin);
        this.workspace = workspace;
        this.logger = winston_1.default.createLogger({
            transports: [
                new winston_1.default.transports.Console(),
            ],
            level: 'info',
            format: winston_1.default.format.simple(),
        });
    }
    start() {
        return __awaiter(this, void 0, void 0, function* () {
            this.logger.info(`${this.constructor.name} uses LSP server bin: ${this.lspServerBin}`);
            try {
                this.lspServer = this.startLspServer();
                const self = this;
                this.lspServer.on('error', (err) => {
                    self.onLspServerError(err);
                });
            }
            catch (err) {
                this.onLspServerError(err);
            }
            this.lspClient = lsp.createMessageConnection(new lsp.StreamMessageReader(this.lspServer.stdout), new lsp.StreamMessageWriter(this.lspServer.stdin));
            this.lspClient.listen();
            yield this.init();
            this.isStarted = true;
        });
    }
    stop() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.lspClient.sendRequest(lsp.ShutdownRequest.type, undefined);
            this.lspServer.kill('SIGINT');
        });
    }
    isMatch(filePath) {
        const fileExt = path.extname(filePath);
        return this.languageIdMap.has(fileExt);
    }
    getDocumentSymbols(filePath) {
        return __awaiter(this, void 0, void 0, function* () {
            const fileUri = (0, url_1.pathToFileURL)(path.resolve(this.workspace, filePath)).toString();
            const didOpenRequest = {
                textDocument: {
                    uri: fileUri,
                    languageId: this.getLanguageId(filePath),
                    version: 1,
                    text: fs_1.default.readFileSync(path.resolve(this.workspace, filePath), { encoding: 'utf-8' }),
                }
            };
            this.lspClient.sendNotification(lsp.DidOpenTextDocumentNotification.type, didOpenRequest);
            try {
                const documentSymbolRequest = {
                    textDocument: lsp.TextDocumentIdentifier.create(fileUri),
                };
                const symbols = yield this.lspClient.sendRequest(lsp.DocumentSymbolRequest.type, documentSymbolRequest);
                return this.flattenSymbols(fileUri, symbols);
            }
            catch (err) {
                this.logger.error(err);
                return null;
            }
            finally {
                const didCloseRequest = {
                    textDocument: lsp.TextDocumentIdentifier.create(fileUri)
                };
                this.lspClient.sendNotification(lsp.DidCloseTextDocumentNotification.type, didCloseRequest);
            }
        });
    }
    startLspServer(cwd) {
        throw new Error("Not implemented");
    }
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            const initRequest = {
                rootUri: (0, url_1.pathToFileURL)(this.workspace).toString(),
                processId: process.pid,
                capabilities: this.getCapabilities(),
                workspaceFolders: null,
            };
            yield this.lspClient.sendRequest(lsp.InitializeRequest.type, initRequest);
            this.logger.info(`${this.constructor.name} has been initialized`);
        });
    }
    getLanguageId(filePath) {
        const fileExt = path.extname(filePath);
        if (!this.languageIdMap.has(fileExt)) {
            throw new Error(`Unsupported file type: ${filePath}`);
        }
        return this.languageIdMap.get(fileExt);
    }
    getCapabilities() {
        return {};
    }
    flattenSymbols(fileUri, symbols, parent) {
        if (symbols.length === 0) {
            return symbols;
        }
        if (symbols[0].hasOwnProperty('location')) {
            return symbols;
        }
        const results = [];
        for (const symbol of symbols) {
            results.push({
                name: symbol.name,
                kind: symbol.kind,
                location: {
                    uri: fileUri,
                    range: symbol.range,
                },
                containerName: parent ? parent : undefined,
            });
            results.push(...this.flattenSymbols(fileUri, symbol.children, symbol.name));
        }
        return results;
    }
    onLspServerError(err) {
        this.logger.error('Start LSP server error: ' + err);
        process.exit(1);
    }
}
exports.CommonLspService = CommonLspService;
