package chaoran.business.adapter;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-02-01          FXY        Created
 **********************************************
 */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.Triggering;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import chaoran.business.R;
import chaoran.business.activity.ResultListener;
import chaoran.business.strategy.Strategy;

/**
 * 优博讯适配器
 */
public class UroBoAdapter implements Adapter {

    private Strategy strategy;
    private Context context;
    private ResultListener resultListener;


    public UroBoAdapter(Context context, ResultListener resultListener) {
        this.context = context;
        this.resultListener = resultListener;
        this.strategy = new Receiver();
    }

    @Override
    public void start() {
        strategy.executeStrategy(resultListener);
    }

    @Override
    public void stop() {
        strategy.exclusiveStrategy();
    }

    /**
     * 广播接受者
     * 自省策略
     */
    public class Receiver extends BroadcastReceiver implements Strategy {

        private ScanManager mScanManager;

        public Receiver() {
            mScanManager = new ScanManager();
            mScanManager.openScanner();
            mScanManager.switchOutputMode(0);
            if (mScanManager.getTriggerMode() != Triggering.CONTINUOUS)
                mScanManager.setTriggerMode(Triggering.CONTINUOUS);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String barcode = intent.getStringExtra("barcode_string");
            resultListener.result(barcode);
        }

        @Override
        public void executeStrategy(ResultListener resultListener) {
            mScanManager.startDecode();
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.ACTION_DECODE_DATA");
            context.registerReceiver(this, filter);
        }

        @Override
        public void exclusiveStrategy() {
            context.unregisterReceiver(this);
            mScanManager.stopDecode();
        }
    }

}
