package lc.ris.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * This class receives intent messages from the Zebra DataWedge application and uses that to process
 * barcodes in the RIS application.
 *
 * @author Alex Leigh
 * @since mk1
 */
public class DataWedgeReceiver extends BroadcastReceiver {
    private final ScanFragment scanFragment;

    public DataWedgeReceiver(ScanFragment scanFragment) {
        this.scanFragment = scanFragment;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(scanFragment.getResources().getString(R.string.activity_intent_filter_action))) {
            try {
                displayScanResult(intent);
            } catch (Exception e) {
                // Do nothing
            }
        }
    }

    /**
     * This method is called when we receive a barcode scan from the Zebra DataWedge, which arrives
     * via an Android intent.
     */
    private void displayScanResult(Intent initiatingIntent) {
        // Every time we get a hardware scan, we clear the contents of the text box.
        String decodedSource = initiatingIntent.getStringExtra(
                scanFragment.getResources().getString(R.string.datawedge_intent_key_source));
        String decodedData = initiatingIntent.getStringExtra(
                scanFragment.getResources().getString(R.string.datawedge_intent_key_data));
        String decodedLabelType = initiatingIntent.getStringExtra(scanFragment.getResources().getString(R.string.datawedge_intent_key_label_type));
        Log.i("RIS", "Received hardware scan: " + decodedData);

        BarcodeBroker broker = ((MainActivity) scanFragment.getActivity()).getBarcodeBroker();
        broker.publish(decodedData);
    }
}
