package net.openmob.mobileimsdk.android.core;

import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import net.openmob.mobileimsdk.android.ClientCoreSDK;
import net.openmob.mobileimsdk.android.conf.IMConfigEntity;

import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class LocalDataReciever {
    private static final String TAG = LocalDataReciever.class.getSimpleName();

    private static volatile LocalDataReciever instance = null;

    // private Context context;
    private LocalDataHandler messageHandler = null;

    private Thread thread = null;

    private boolean init = false;

    public static LocalDataReciever getInstance() {
        if (instance == null)
            synchronized (LocalDataReciever.class) {
                if (instance == null) {
                    instance = new LocalDataReciever();
                }
            }
        return instance;
    }

    private LocalDataReciever() {
        init();
    }

    private void init() {
        if (!this.init) {
            HandlerThread thread = new HandlerThread("UDP_DATA_RECIVER_TASK");
            thread.start();
            this.messageHandler = new LocalDataHandler(thread.getLooper());
            this.init = true;
        }
    }

    public void stop() {
        if (this.thread != null) {
            this.thread.interrupt();
            this.thread = null;
        }
    }

    public void startup() {
        this.stop();
        try {
            this.thread = new Thread(() -> {
                try {
                    if (ClientCoreSDK.DEBUG){
                        Log.i(TAG, "【IMCORE】本地UDP端口侦听中，端口=" + IMConfigEntity.localPort + "...");
                    }
                    udpListeningImpl();
                } catch (Exception e) {
                    Log.i(TAG, "【IMCORE】本地UDP监听停止了(socket被关闭了?)：" + e.getMessage() + "，应该是用户退出登陆或网络断开了。");
                }
            });
            this.thread.start();
        } catch (Exception ee) {
            Log.i(TAG, "【IMCORE】本地UDPSocket监听开启时发生异常," + ee.getMessage(), ee);
        }
    }

    public boolean isInit() {
        return this.init;
    }

    private void udpListeningImpl() throws Exception {
        while (true) {
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            DatagramSocket localUDPSocket = LocalSocketProvider.getInstance().getLocalSocket();
            if (localUDPSocket != null && !localUDPSocket.isClosed()) {
                localUDPSocket.receive(packet);
                Message m = Message.obtain();
                m.obj = packet;
                this.messageHandler.sendMessage(m);
            }
        }
    }
}
