odoo.define('my_module.barcode_handler', function (require) {
    "use strict";

    var core = require('web.core');
    var registry = require('web.field_registry');
    var session = require('web.session');
    var FieldChar = require('web.basic_fields').FieldChar;

    var _t = core._t;

    var BarcodeHandlerField = FieldChar.extend({
        init: function () {
            this._super.apply(this, arguments);
            this.scanInProgress = false;
        },
        willStart: function () {
            return this._super.apply(this, arguments).then(() => {
                var barcode = this.call('barcode', 'get_barcode');
                if (barcode) {
                    this._onBarcodeScanned(barcode);
                }
                this.call('barcode', 'start_listening');
            });
        },
        destroy: function () {
            this.call('barcode', 'stop_listening');
            this._super.apply(this, arguments);
        },
        _onBarcodeScanned: function (barcode) {
            if (this.scanInProgress) {
                return;
            }
            this.scanInProgress = true;
            var self = this;
            session.rpc('/mrp_barcode/scan_to_open_report_from_form', { barcode: barcode }).then(function (result) {
                self.scanInProgress = false;
                self.$el.val(result);
                self.trigger_up('field_changed', {
                    dataPointID: self.dataPointID,
                    changes: { value: result },
                });
            });
        },
    });

    registry.add('barcode_handlerr', BarcodeHandlerField);

    return {
        BarcodeHandlerField: BarcodeHandlerField,
    };
});