package de.trbnb.databindingcommands.command

import de.trbnb.databindingcommands.DisabledCommandInvocationException
import java.lang.ref.WeakReference

/**
 * Base class for standard [Command] implementations.

 * An implementation of the [Command.isEnabled] is not given.
 *
 * @param action The initial action that will be run when the Command is executed.
 */
@Deprecated("This library is deprecated and migrated into MvvmBase (https://github.com/trbnb/mvvmbase)")
abstract class BaseCommandImpl<out R>(private val action: () -> R) : Command<R> {

    private val listeners: MutableList<WeakReference<(Boolean) -> Unit>> = mutableListOf()

    final override fun invoke(): R {
        if(!isEnabled){
            throw DisabledCommandInvocationException()
        }

        return action()
    }

    /**
     * This method should be called when the result of [isEnabled] might have changed.
     */
    protected fun triggerEnabledChangedListener() {
        listeners.forEach {
            it.get()?.invoke(isEnabled)
        }
    }

    override fun addEnabledListener(listener: (Boolean) -> Unit) {
        listeners.add(WeakReference(listener))
    }

    override fun removeEnabledListener(listener: (Boolean) -> Unit) {
        listeners.removeAll { it.get() == listener }
    }

    override fun clearEnabledListeners() {
        listeners.clear()
    }


}
