1'use strict';
2const EventEmitter = require('events');
3
4class PayboxClient extends EventEmitter{
5    constructor(options){
6        super();
7        if(!options || !options.xpPrductKey || !options.xpDeviceSecret){
8            throw new Error('device info error');
9        }
10
11        this.options = {
12            mqttPrductKey: options.mqttPrductKey ? options.mqttPrductKey : 'null',
13            supplierId: options.supplierId ? options.supplierId : 'null',
14            itemId: options.itemId ? options.itemId : 'null',
15            boxModel: options.boxModel ? options.boxModel : 'null',
16            boxVersion: options.boxVersion ? options.boxVersion : 'null',
17            xpPrductKey: options.xpPrductKey,
18            xpPrductSecret: options.xpPrductSecret ? options.xpPrductSecret : 'null',
19            xpDeviceSecret: options.xpDeviceSecret
20        }
21        this.fail = options.fail || function(){};
22        this.success = options.success || function(){};
23        this.opened = false;
24        this.onFlag = false;
25        this._open();
26        this._on();
27    }
28
29    _open() {
30        this.payboxInstance = __native.PAYBOX.open(this.options);
31        if (this.payboxInstance < 0) {
32            this.fail();
33            return;
34        }
35        this.opened = true;
36        this.success();
37    }
38
39    _on() {
40        if (this.payboxInstance < 0) {
41            throw new Error("PAYBOX not init");
42        }
43
44        __native.PAYBOX.on(this.payboxInstance, function(event, data){
45            this.emit(event, data);
46        }.bind(this));
47
48    };
49
50    close() {
51        if(this.payboxInstance < 0){
52            throw new Error('device not init...');
53        }
54        var ret = __native.PAYBOX.close(this.payboxInstance);
55        if (ret != 0) {
56            this.emit('error', 'paybox client close falied')
57            return
58        }
59        this.opened = false;
60        this.emit('close');
61    }
62}
63
64function open(options){
65    return new PayboxClient(options);
66}
67
68module.exports = {
69    open,
70}
71
72
73