package com.coder.toolbox.views

import com.coder.toolbox.cli.CoderCLIManager
import com.coder.toolbox.sdk.v2.models.Workspace
import com.coder.toolbox.sdk.v2.models.WorkspaceAgent
import com.coder.toolbox.settings.ReadOnlyCoderSettings
import com.jetbrains.toolbox.api.remoteDev.environments.SshEnvironmentContentsView
import com.jetbrains.toolbox.api.remoteDev.ssh.SshConnectionInfo
import java.net.URL

/**
 * A view for a single environment.  It displays the projects and IDEs.
 *
 * This just delegates to the SSH view provided by Toolbox, all we have to do is
 * provide the host name.
 *
 * SSH must be configured before this will work.
 */
class EnvironmentView(
    private val settings: ReadOnlyCoderSettings,
    private val url: URL,
    private val workspace: Workspace,
    private val agent: WorkspaceAgent,
) : SshEnvironmentContentsView {
    override suspend fun getConnectionInfo(): SshConnectionInfo = object : SshConnectionInfo {
        /**
         * The host name generated by the cli manager for this workspace.
         */
        override val host: String = resolveHost()

        /**
         * The port is ignored by the Coder proxy command.
         */
        override val port: Int = 22

        /**
         * The username is ignored by the Coder proxy command.
         */
        override val userName: String? = null

    }

    private fun resolveHost(): String =
        if (settings.isSshWildcardConfigEnabled)
            CoderCLIManager.getWildcardHostname(url, workspace, agent)
        else CoderCLIManager.getHostname(url, workspace, agent)
}