package net.openmob.mobileimsdk.android.core;

import android.util.Log;

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

import java.net.DatagramSocket;


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

    private static LocalSocketProvider instance = null;

    private DatagramSocket localSocket = null;

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

    public DatagramSocket resetLocalSocket() {
        try {
            this.closeLocalSocket();
            this.localSocket = (IMConfigEntity.localPort == 0) ? new DatagramSocket() : new DatagramSocket(IMConfigEntity.localPort);
            this.localSocket.setReuseAddress(true);
            return this.localSocket;
        } catch (Exception e) {
            Log.i(TAG, "【IMCORE】localUDPSocket创建时出错，原因是：" + e.getMessage(), e);
            this.closeLocalSocket();
            return null;
        }
    }

    private boolean isLocalSocketReady() {
        return (this.localSocket != null && !this.localSocket.isClosed());
    }

    public DatagramSocket getLocalSocket() {
        if (isLocalSocketReady())
            return this.localSocket;
        return resetLocalSocket();
    }

    public void closeLocalSocket() {
        closeLocalSocket(true);
    }

    public void closeLocalSocket(boolean silent) {
        try {
            if (ClientCoreSDK.DEBUG && !silent)
                Log.i(TAG, "【IMCORE】正在closeLocalUDPSocket()...");
            if (this.localSocket != null) {
                this.localSocket.close();
                this.localSocket = null;
            } else if (!silent) {
                Log.i(TAG, "【IMCORE】Socket处于未初化状态（可能是您还未登陆），无需关闭。");
            }
        } catch (Exception e) {
            if (!silent)
                Log.i(TAG, "【IMCORE】lcloseLocalUDPSocket时出错，原因是：" + e.getMessage(), e);
        }
    }
}
