package com.beem.project.beem.utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.widget.Toast;

import com.beem.project.beem.ui.Login;

/**
 * Manage broadcast disconnect intent.
 * @author nikita
 */
public class BeemBroadcastReceiver extends BroadcastReceiver {

    /**
     * Broadcast intent type.
     */
    public static final String BEEM_CONNECTION_CLOSED = "BeemConnectionClosed";
    private ServiceConnection mService;
    private boolean mIsBinded;

    /**
     * constructor.
     * @param service service observed
     */
    public BeemBroadcastReceiver(final ServiceConnection service) {
	mService = service;
	mIsBinded = false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onReceive(Context context, Intent intent) {
	Log.d("Broadcast", "onReceive");
	if (mIsBinded)
	    context.unbindService(mService);
	setBinded(false);
	// start activity if unexpected disconnection
	if (!intent.getBooleanExtra("normally", false))
	    context.startActivity(new Intent(context, Login.class));
	CharSequence message = intent.getCharSequenceExtra("message");
	Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	if (context instanceof Activity) {
	    Activity act = (Activity) context;
	    act.finish();
	}
    }

    /**
     * service is binded.
     * @param binded the state of the bind.
     */
    public void setBinded(boolean binded) {
	mIsBinded = binded;
    }

    /**
     * return service bind status.
     * @return service bind status.
     */
    public boolean isBinded() {
	return mIsBinded;
    }
}
