/**
 * 
 */
package com.beem.project.beem.ui;

import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;

import com.beem.project.beem.BeemService;
import com.beem.project.beem.R;
import com.beem.project.beem.service.PresenceAdapter;
import com.beem.project.beem.service.aidl.IXmppFacade;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author nikita
 *
 */
public class Subscription extends Activity {

    public static final String TAG = "Subscription";
    private IXmppFacade mService;
    private String mContact;
    private ServiceConnection mServConn = new BeemServiceConnection();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.subscription);
	bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
	findViewById(R.id.SubscriptionAccept).setOnClickListener(mClickListener);
	findViewById(R.id.SubscriptionRefuse).setOnClickListener(mClickListener);
	mContact = getIntent().getStringExtra("from");
	TextView tv = (TextView) findViewById(R.id.SubscriptionText);
	String str = String.format(getString(R.string.SubscriptText), mContact);
	tv.setText(str);
    }

    @Override
    protected void onDestroy() {
	super.onDestroy();
	unbindService(mServConn);
    }

    private OnClickListener mClickListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    switch (v.getId()) {
		case R.id.SubscriptionAccept:
		    Presence presence = new Presence(Type.subscribed);
		    presence.setTo(mContact);
		    PresenceAdapter preAdapt = new PresenceAdapter(presence);
		    try {
			mService.sendPresencePacket(preAdapt);
			Toast.makeText(Subscription.this, getString(R.string.SubscriptAccept),
			    Toast.LENGTH_SHORT).show();
			finish();
		    } catch (RemoteException e) {
			Toast.makeText(Subscription.this, getString(R.string.SubscriptError),
			    Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		    }
		    break ;
		case R.id.SubscriptionRefuse:
		    Toast.makeText(Subscription.this, getString(R.string.SubscriptRefused),
			Toast.LENGTH_SHORT).show();

		    break ;
		default:
		    Toast.makeText(Subscription.this, getString(R.string.SubscriptError),
			Toast.LENGTH_SHORT).show();
	    };
	}
    };

    private class BeemServiceConnection implements ServiceConnection {

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mService = IXmppFacade.Stub.asInterface(service);			
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
	    mService = null;
	}
    }
}
