package net.openmob.mobileimsdk.android.core;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import net.openmob.mobileimsdk.android.ClientCoreSDK;
import net.openmob.mobileimsdk.android.utils.MBThreadPoolExecutor;

import java.util.concurrent.atomic.AtomicBoolean;


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

    private static AutoReLoginDaemon instance = null;

    public static int AUTO_RE$LOGIN_INTERVAL = 2000;

    private Handler handler = null;

    private Runnable runnable = null;

    private AtomicBoolean autoReLoginRunning = new AtomicBoolean(false);

    private AtomicBoolean _excuting = new AtomicBoolean(false);

    private boolean init = false;

    //  private Observer debugObserver;

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

    private AutoReLoginDaemon() {
        init();
    }

    private void init() {
        if (!this.init) {
            this.handler = new Handler();
            this.runnable = (() -> {
                if (!this._excuting.get()) {
                    MBThreadPoolExecutor.runInBackground(new Runnable() {
                        @Override
                        public void run() {
                            doSendLogin();
                        }
                    });
                }
            });
            this.init = true;
        }
    }

    private void doSendLogin() {
        this._excuting.compareAndSet(false, true);
        if (ClientCoreSDK.DEBUG) {
            Log.d(AutoReLoginDaemon.TAG, "【IMCORE】自动重新登陆线程执行中, autoReLogin?" + ClientCoreSDK.autoReLogin + "...");
        }
        int code = -1;
        if (ClientCoreSDK.autoReLogin) {
            code = LocalDataSender.getInstance().sendLogin();
        }

        if (code == 0) {
            LocalDataReciever.getInstance().startup();
        }
        this._excuting.compareAndSet(true, false);
        this.handler.postDelayed(this.runnable, AUTO_RE$LOGIN_INTERVAL);
        ClientCoreSDK.getInstance().getImEvent().onLinKing(1);
        ClientCoreSDK.getInstance().setConnectedToServer(false);
        //Log.d(TAG,"XXX1S");
    }


    public void stop() {
        this.handler.removeCallbacks(this.runnable);
        this.autoReLoginRunning.compareAndSet(true, false);
    }

    public void start(boolean immediately) {
        this.stop();
        this.handler.postDelayed(this.runnable, immediately ? 0L : AUTO_RE$LOGIN_INTERVAL);
        this.autoReLoginRunning.compareAndSet(false, true);

    }

    public boolean isAutoReLoginRunning() {
        return this.autoReLoginRunning.get();
    }


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

}

