package com.sshproxy.vpn.service

import android.os.Handler
import android.os.Looper
import com.sshproxy.vpn.ssh.SshTunnelManager
import com.sshproxy.vpn.util.CallsAvailabilityStatus
import com.sshproxy.vpn.util.TunnelTransport

object TunnelServiceHolder {
    var sshManager: SshTunnelManager? = null
        internal set

    data class StateSnapshot(
        val state: TunnelService.State,
        val message: String,
        val transport: TunnelTransport?,
        val callsStatus: CallsAvailabilityStatus?
    )

    private val mainHandler = Handler(Looper.getMainLooper())
    private var lastState: StateSnapshot? = null
    private var stateListener: ((
        TunnelService.State,
        String,
        TunnelTransport?,
        CallsAvailabilityStatus?
    ) -> Unit)? = null
    private var nativeErrorListener: ((String) -> Unit)? = null

    fun setStateListener(
        listener: ((
            TunnelService.State,
            String,
            TunnelTransport?,
            CallsAvailabilityStatus?
        ) -> Unit)?
    ) {
        stateListener = listener
        lastState?.let { snapshot ->
            listener?.invoke(
                snapshot.state,
                snapshot.message,
                snapshot.transport,
                snapshot.callsStatus
            )
        }
    }

    fun setNativeErrorListener(listener: ((String) -> Unit)?) {
        nativeErrorListener = listener
    }

    internal fun updateState(
        state: TunnelService.State,
        message: String,
        transport: TunnelTransport? = null,
        callsStatus: CallsAvailabilityStatus? = null
    ) {
        lastState = StateSnapshot(state, message, transport, callsStatus)
        mainHandler.post {
            stateListener?.invoke(state, message, transport, callsStatus)
        }
    }

    internal fun clearState() {
        lastState = null
    }

    internal fun onNativeError(message: String) {
        nativeErrorListener?.invoke(message)
    }
}
