package lc.ris.android;

import android.util.Log;

import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;

/**
 * This is a simple implementation of an in-memory message broker for handling barcode messages. It exists
 * since Android does not seem to have a way for a {@link androidx.fragment.app.Fragment} to register for intents,
 * so the Google-provided intent messaging system is not suitable for IPC within the application.
 *
 * The intention is for the {@link android.app.Activity} to contain an instance of this class, which it would
 * then perhaps make available via a getter. Interested classes would then access the broker by calling this
 * getter on the activity, where they can register & unregister listeners as their lifecycle progresses. To
 * protect against memory leaks, this implementation only holds weak references to receivers.
 *
 * Note that this class just transports the scanned transport; it is up to other code within RIS to make sense
 * of the barcode and to decode the contents and associate it with an entityId.
 *
 * @author Alex Leigh
 * @since mk1
 */
public class BarcodeBroker {
    private final Set<BarcodeListener> weakHashSet = Collections.newSetFromMap(new WeakHashMap<>());

    public void addListener(final BarcodeListener listener) {
        weakHashSet.add(listener);
    }

    public void removeListener(final BarcodeListener listener) {
        weakHashSet.remove(listener);
    }

    public void publish(final String scannedCode) {
        Log.i("RIS", "Publishing barcode scan: " + scannedCode);
        for (BarcodeListener listener : weakHashSet) {
            listener.receiveBarcode(scannedCode);
        }
    }
}
