1'use strict';
2
3const EventEmitter = require('events');
4
5function stringToBytesArray(str) {
6    var ch, st, re = [];
7    for (var i = 0; i < str.length; i++ ) {
8        ch = str.charCodeAt(i);
9        st = [];
10       do {
11            st.push(ch & 0xFF);
12            ch = ch >> 8;
13        }
14        while ( ch );
15        re = re.concat(st.reverse());
16    }
17    return re;
18}
19
20class UDPClient extends EventEmitter {
21    constructor() {
22        super();
23        this.udpClientInstance = __native.UDP.createSocket();
24        this.localPort = 0;
25    }
26
27    bind(port) {
28        this.localPort = port || 0;
29        if(__native.UDP.bind(this.udpClientInstance, this.localPort) < 0) {
30            throw new Error("bind error");
31        }
32        this._onListening();
33    };
34
35    send(options) {
36        if (!(options.message instanceof Array)) {
37            options.message = stringToBytesArray(options.message);
38        }
39        __native.UDP.sendto(this.udpClientInstance, options, function(ret) {
40            if (ret < 0) {
41                this.emit('error', 'udp send error');
42                if(options.fail) options.fail();
43                return;
44            }
45            this.emit('send', 'udp send success');
46            if(options.success) options.success();
47        }.bind(this));
48    };
49
50    close() {
51        var ret = __native.UDP.close(this.udpClientInstance);
52        if (ret < 0) {
53            console.log('close udp socket faild');
54            return;
55        }
56        this.emit('close', 'udp client close');
57    };
58
59    _onListening() {
60        __native.UDP.recvfrom(this.udpClientInstance, function(data, rinfo, err) {
61            if (err === -4) {
62                this.emit('error', 'udp client receive data error');
63                return;
64            }
65            if (err > 0) {
66                this.emit('message', data, rinfo);
67            }
68        }.bind(this));
69    };
70}
71
72function createSocket(options) {
73    return new UDPClient(options);
74}
75
76module.exports = {
77    createSocket,
78}