/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

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

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.beem.project.beem.R;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.service.aidl.IBeemJingleListener;
import com.beem.project.beem.service.aidl.IJingle;
import com.beem.project.beem.service.aidl.IXmppFacade;

/**
 * This class is an activity which display an animation during the connection with the server.
 * @author Da Risk <darisk972@gmail.com>
 */
public class Call extends Activity {

    private static final Intent SERVICE_INTENT = new Intent();
    static {
	SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
    }
    private ImageView mLogo;
    private TextView mCallInfo;
    private Animation mRotateAnim;
    private final ServiceConnection mServConn = new BeemServiceConnection();
    private BeemJingleSessionListener mJingleListener = new BeemJingleSessionListener();
    private IXmppFacade mXmppFacade;
    private final Handler mHandler = new Handler();
    private Button mCloseCall;
    private Button mAcceptCall;
    private IJingle mJingle;
    private Intent mIntent;

    final static long[] vibratePattern = {0,1000,1000};

    public static final int UA_STATE_IDLE = 0;
    public static final int UA_STATE_INCOMING_CALL = 1;
    public static final int UA_STATE_OUTGOING_CALL = 2;
    public static final int UA_STATE_INCALL = 3;
    public static final int UA_STATE_HOLD = 4;

    public static int call_state = UA_STATE_IDLE;
    public static int docked = -1,headset = -1;
    public static Ringtone oRingtone;
    public static Context mContext;

    public static void stopRingtone() {
	android.os.Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
	v.cancel();
	if (oRingtone != null) {
	    Ringtone ringtone = oRingtone;
	    oRingtone = null;
	    ringtone.stop();
	}
    }

    public static void startRingtone() {
	android.os.Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
	v.vibrate(vibratePattern,1);
	oRingtone = RingtoneManager.getRingtone(mContext, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
	oRingtone.play();
    }

    /**
     * Constructor.
     */
    public Call() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	Call.mContext = this;
	setContentView(R.layout.call);
	mIntent = this.getIntent();

	mLogo = (ImageView) findViewById(R.id.call_logo_anim);
	mRotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_and_scale);
	mCloseCall = (Button) findViewById(R.id.call_cancel_button);
	mCloseCall.setOnClickListener(new ClickListener());
	if (mIntent.getBooleanExtra("isCaller", false)) {
	    mAcceptCall = (Button) findViewById(R.id.call_accept_button);
	    mAcceptCall.setVisibility(View.GONE);
	    call_state = UA_STATE_OUTGOING_CALL;
	} else {
	    mAcceptCall = (Button) findViewById(R.id.call_accept_button);
	    mAcceptCall.setOnClickListener(new ClickListener());
	    call_state = UA_STATE_INCOMING_CALL;
	    Call.startRingtone();
	}
	mCallInfo = (TextView) findViewById(R.id.call_info);
    }

    @Override
    protected void onStart() {
	super.onStart();
	mLogo.startAnimation(mRotateAnim);
    }

    @Override
    protected void onResume() {
	super.onResume();
	if (mXmppFacade == null)
	    bindService(Call.SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
	super.onPause();
	if (mXmppFacade != null) {
	    try {
		mJingle.removeJingleListener(mJingleListener);
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	    unbindService(mServConn);
	    mXmppFacade = null;
	}
    }

    @Override
    public final boolean onCreateOptionsMenu(Menu menu) {
	super.onCreateOptionsMenu(menu);
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.call, menu);
	return true;
    }

    /**
     * Callback for menu item selected.
     * @param item the item selected
     * @return true on success, false otherwise
     */
    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.call_speaker_on:
		try {
		    mJingle.setSpeakerMode(AudioManager.MODE_NORMAL);
		} catch (RemoteException e) {
		    e.printStackTrace();
		}
		return true;
	    case R.id.call_speaker_off:
		try {
		    mJingle.setSpeakerMode(AudioManager.MODE_IN_CALL);
		} catch (RemoteException e) {
		    e.printStackTrace();
		}
		return true;
	    case R.id.call_hold_on:
		Call.call_state = UA_STATE_HOLD;
		return true;
	    case R.id.call_hold_off:
		Call.call_state = UA_STATE_INCALL;
		return true;
	    default:
		return false;
	}
    }

    /**
     * Click event listener on cancel button.
     */
    private class ClickListener implements OnClickListener {

	/**
	 * Constructor.
	 */
	ClickListener() {
	}

	@Override
	public void onClick(View v) {
	    try {
		if (v == mCloseCall) {
		    mJingle.closeCall();
		    stopRingtone();
		    Call.call_state = UA_STATE_IDLE;
		} else if (v == mAcceptCall) {
		    mJingle.acceptCall();
		    stopRingtone();
		    Call.call_state = UA_STATE_INCALL;
		}
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	    finish();
	}
    }

    private class BeemJingleSessionListener extends IBeemJingleListener.Stub {

	/**
	 * Refresh the call activity.
	 */
	private class RunnableChange implements Runnable {

	    private String mStr;
	    /**
	     * Constructor.
	     */
	    public RunnableChange(String str) {
		mStr = str;
	    }

	    /**
	     * {@inheritDoc}
	     */
	    @Override
	    public void run() {
		mCallInfo.setText(mStr);
	    }
	}

	public BeemJingleSessionListener() {
	}

	@Override
	public void sessionClosed(final String reason) {
	    android.util.Log.d("TEST", "TEST " + reason);
	    Call.stopRingtone();
	    call_state = UA_STATE_IDLE;
	    mHandler.post(new RunnableChange(reason));
	}

	@Override
	public void sessionDeclined(final String reason)  {
	    android.util.Log.d("TEST", "TEST4 " + reason);
	    Call.stopRingtone();
	    call_state = UA_STATE_IDLE;
	    mHandler.post(new RunnableChange(reason));
	}

	@Override
	public void sessionClosedOnError(final String error) {
	    android.util.Log.d("TEST", "TEST5 " + error);
	    Call.stopRingtone();
	    call_state = UA_STATE_IDLE;
	    mHandler.post(new RunnableChange(error));
	}

	@Override
	public void sessionEstablished() {
	    android.util.Log.d("TEST", "TEST2 ");
	    call_state = UA_STATE_INCALL;
	    Call.stopRingtone();
	    mHandler.post(new RunnableChange("established"));
	}

	@Override
	public void sessionRequested(final String fromJID) {
	    android.util.Log.d("TEST", "TEST3 " + fromJID);
	    mHandler.post(new RunnableChange(fromJID));
	}
    }

    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {

	private Contact mContact;

	/**
	 * Constructor.
	 */
	public BeemServiceConnection() {
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mXmppFacade = IXmppFacade.Stub.asInterface(service);
	    try {
		mJingle = mXmppFacade.getJingleService();
		mJingle.addJingleListener(mJingleListener);
		mContact = new Contact(getIntent().getData());
		mJingle.call(mContact.getJIDWithRes());
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	}

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