/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.fenix.home

import android.content.Context
import org.mozilla.fenix.tor.TorController
import org.mozilla.fenix.tor.TorEvents
import org.mozilla.fenix.tor.bootstrap.TorQuickStart
import org.mozilla.fenix.browser.browsingmode.BrowsingMode
import org.mozilla.fenix.browser.browsingmode.BrowsingModeManager

/**
 * Describes various states of the home fragment UI.
 */
sealed class Mode {
    object Normal : Mode()
    object Private : Mode()
    object Bootstrap : Mode()

    companion object {
        fun fromBrowsingMode(browsingMode: BrowsingMode) = when (browsingMode) {
            BrowsingMode.Normal -> Normal
            BrowsingMode.Private -> Private
        }
    }
}

@SuppressWarnings("LongParameterList", "TooManyFunctions")
class CurrentMode(
    private val context: Context,
    private val torQuickStart: TorQuickStart,
    private val shouldStartTor: Boolean,
    private val torController: TorController,
    private val browsingModeManager: BrowsingModeManager,
    private val dispatchModeChanges: (mode: Mode) -> Unit
) : TorEvents {

    init {
        torController.registerTorListener(this)
    }

    fun getCurrentMode() = if (shouldStartTor && (!torQuickStart.quickStartTor() && !torController.isBootstrapped)) {
        Mode.Bootstrap
    } else {
        Mode.fromBrowsingMode(browsingModeManager.mode)
    }

    fun emitModeChanges() {
        dispatchModeChanges(getCurrentMode())
    }

    @SuppressWarnings("EmptyFunctionBlock")
    override fun onTorConnecting() {
    }

    override fun onTorConnected() {
        dispatchModeChanges(getCurrentMode())
    }

    override fun onTorStopped() {
        dispatchModeChanges(getCurrentMode())
    }

    @SuppressWarnings("EmptyFunctionBlock")
    override fun onTorStatusUpdate(entry: String?, status: String?) {
    }

    fun unregisterTorListener() {
        torController.unregisterTorListener(this)
    }
}
