package epson.server.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;

import epson.print.Util.EPLog;
import epson.print.Util.Utils;

public class NetworkConnectivityListener {
    public static final int CREATE_DIALOG = 1;
    private static final int DOWNLOAD_FINISH = 4;
    private boolean isOnline;
    private Handler mActivityHandler;
    private Context mContext;
    private boolean mListening;
    private ConnectivityBroadcastReceiver mReceiver = new ConnectivityBroadcastReceiver();

    public NetworkConnectivityListener(Handler handler) {
        mActivityHandler = handler;
    }

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
        private ConnectivityBroadcastReceiver() {
        }

        public void onReceive(Context context, Intent intent) {
            if (Utils.getInstance().isNetworkAvailable(context)) {
                boolean unused = isOnline = true;
                EPLog.e("ConnectivityBroadcastReceiver:  ", "===========OKKKKKKKKKKKKKKKKKKKK");
                return;
            }
            boolean unused2 = isOnline = false;
            cancelDownload();
            EPLog.e("ConnectivityBroadcastReceiver:  ", "============FALSEEEEEEEEEEEEEEEEE");
        }

        private void cancelDownload() {
            mActivityHandler.sendEmptyMessage(4);
            Message message = new Message();
            message.what = 1;
            message.arg1 = 1;
            mActivityHandler.sendMessage(message);
            stopListening();
        }
    }

    public synchronized void startListening(Context context) {
        if (!mListening) {
            mContext = context;
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            context.registerReceiver(mReceiver, intentFilter);
            mListening = true;
        }
    }

    public synchronized void stopListening() {
        if (mListening) {
            mContext.unregisterReceiver(mReceiver);
            mContext = null;
            mListening = false;
        }
    }

    public boolean getIsOnline() {
        return isOnline;
    }
}
