import extend from './extend.js';

// var main, IntentFilter, filter, receiver, options;

/**
 * 扫描广播接收器
 */
class Receiver {
    main = null;
    IntentFilter = null;
    filter = null;
    receiver = null;
    options = null;

    /**
     * @param {object} opts 参数
     * @param {string} opts.action - 监听动作
     * @param {Function} opts.success - 监听监听成功回调函数
     */
    constructor(opts) {
        this.init(opts);
    }

    /**
     * 初始化
     * @param {Object} opts - 参数
     * @param {string} opts.action - 监听动作
     * @param {Function} opts.success - 监听监听成功回调函数
     */
    init(opts) {
        this.parseOptions(opts);
        let _this = this;
        this.main = plus.android.runtimeMainActivity();
        this.IntentFilter = plus.android.importClass('android.content.IntentFilter');
        this.filter = new this.IntentFilter();
        this.filter.addAction(this.options.action);
        this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
            onReceive: function(context, intent) {
                plus.android.importClass(intent);
                let code = intent.getStringExtra('data');
                code = extend.deleteEndLineFeed(code).trim();
                _this.scanSuccess(code);
            }
        });
    }

    start() {
        this.main.registerReceiver(this.receiver, this.filter);
    }

    stop() {
        this.main.unregisterReceiver(this.receiver);
    }

    parseOptions(opts) {
        if (!extend.isObject(opts)) {
            opts = {};
        }
        if (extend.isEmptyString(opts.action)) {
            opts.action = 'com.honeywell.scan.broadcast';
        }
        this.options = opts;
    }

    scanSuccess(code) {
        if (typeof this.options.success === 'function') {
            this.options.success(code);
        }
    }
}

export default Receiver;