package me.zhouxi.slint.lsp

import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.lsp.api.LspServer
import com.intellij.platform.lsp.api.LspServerSupportProvider
import com.intellij.platform.lsp.api.ProjectWideLspServerDescriptor
import com.intellij.platform.lsp.api.lsWidget.LspServerWidgetItem
import me.zhouxi.slint.SlintRuntime
import me.zhouxi.slint.icons.SlintIcons
import me.zhouxi.slint.lang.SlintFileType

class SlintLspServerSupportProvider : LspServerSupportProvider {
    override fun fileOpened(
        project: Project,
        file: VirtualFile,
        serverStarter: LspServerSupportProvider.LspServerStarter
    ) {
        if (file.fileType == SlintFileType) {
            serverStarter.ensureServerStarted(SlintLspServerDescriptor(project))
        }
    }


    override fun createLspServerWidgetItem(
        lspServer: LspServer,
        currentFile: VirtualFile?
    ) =
        LspServerWidgetItem(
            lspServer, currentFile,
            SlintIcons.Primary,
        )

    private class SlintLspServerDescriptor(project: Project) : ProjectWideLspServerDescriptor(project, "Slint") {
        override fun isSupportedFile(file: VirtualFile) = file.fileType == SlintFileType
        override fun createCommandLine(): GeneralCommandLine {
            val line = GeneralCommandLine(SlintRuntime.LspExecutable.toAbsolutePath().toString())

            return line
        }
    }
}
