/*
   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 java.util.ArrayList;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.BeemIntent;
import com.beem.project.beem.BeemService;
import com.beem.project.beem.R;
import com.beem.project.beem.ui.dialogs.builders.ChangeStatus;
import com.beem.project.beem.ui.wizard.AccountConfigure;

/**
 * This class is the main Activity for the Beem project.
 * @author Vincent V. <marseille@beem-project.com>
 */
public class Login extends Activity {

    private BeemAccountList mAdapterAccountList;
    private List<String> mListAccount = new ArrayList<String>();
    private final BeemAccountListOnClick mOnAccountClick = new BeemAccountListOnClick();
    private final BroadcastReceiver mOnBroadcastReceiver = new BeemBroadcastReceiver();

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	AccountManager am = AccountManager.get(Login.this);
	Account allAccount[] = am.getAccountsByType(BeemApplication.BEEM_PACKAGE);
	for (Account account : allAccount) {
	    mListAccount.add(account.name);
	}

	setContentView(R.layout.login);

	Intent intent = new Intent(this, BeemService.class);
	startService(intent);

	IntentFilter filter = new IntentFilter(BeemIntent.ACTION_CONNECTED);
	filter.addAction(BeemIntent.ACTION_DISCONNECTED);
	registerReceiver(mOnBroadcastReceiver, filter);

	ListView listView = (ListView) findViewById(R.id.accountlist);
	mAdapterAccountList = new BeemAccountList(getLayoutInflater());
	listView.setClickable(true);
	listView.setOnItemClickListener(mOnAccountClick);
	listView.setAdapter(mAdapterAccountList);
    }

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

    @Override
    public void onStart() {
	super.onStart();
	//TODO: Option autostart connect account
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
	unregisterReceiver(mOnBroadcastReceiver);
    }

    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
	boolean result;
	switch (item.getItemId()) {
	    case R.id.login_create_account:
		startActivity(new Intent(Login.this, AccountConfigure.class));
		result = true;
		break;
	    case R.id.login_menu_about:
		createAboutDialog();
		result = true;
		break;
	    default:
		result = false;
		break;
	}
	return result;
    }

    /**
     * Create an about "BEEM" dialog.
     */
    private void createAboutDialog() {
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	String versionname;
	try {
	    PackageManager pm = getPackageManager();
	    PackageInfo pi = pm.getPackageInfo("com.beem.project.beem", 0);
	    versionname = pi.versionName;
	} catch (PackageManager.NameNotFoundException e) {
	    versionname = "";
	}
	String title = getString(R.string.login_about_title, versionname);
	builder.setTitle(title).setMessage(R.string.login_about_msg).setCancelable(false);
	builder.setNeutralButton(R.string.login_about_button, new DialogInterface.OnClickListener() {

	    public void onClick(DialogInterface dialog, int whichButton) {
		dialog.cancel();
	    }
	});
	AlertDialog aboutDialog = builder.create();
	aboutDialog.show();
    }

    /**
     * Populate row account.
     */
    private class BeemAccountList extends BaseAdapter {

	private LayoutInflater mInflater;

	public BeemAccountList(LayoutInflater layoutInflater) {
	    mInflater = layoutInflater;
	}

	@Override
	public int getCount() {
	    return mListAccount.size();
	}

	@Override
	public Object getItem(int position) {
	    return mListAccount.get(position);
	}

	@Override
	public long getItemId(int position) {
	    return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    View v = convertView;
	    if (convertView == null) {
		v = mInflater.inflate(R.layout.login_row_account, null);
	    }

	    String accountName = mListAccount.get(position);

	    //Check if already connected
	    Intent intent = new Intent(BeemIntent.ACTION_ISCONNECTED);
	    intent.putExtra(BeemIntent.EXTRA_ACCOUNT, accountName);
	    startService(intent);

	    ImageButton logo = (ImageButton) v.findViewById(R.id.loginanim_logo_anim);

	    logo.setFocusable(false);
	    logo.setOnClickListener(new BeemConnectionOnClick(v));
	    logo.setOnLongClickListener(new BeemConnectionOnLongClick(v));

	    TextView name = (TextView) v.findViewById(R.id.accountname);
	    name.setText(accountName);

	    int hash = accountName.hashCode();
	    if (hash < 0)
		hash = hash * -1;
	    v.setId(hash);

	    return v;
	}

    }

    /**
     * Event simple click on item of the button of account list.
     */
    private class BeemConnectionOnClick implements android.view.View.OnClickListener {
	private View mView;

	/**
	 * Constructor.
	 */
	public BeemConnectionOnClick(View v) {
	    mView = v;
	}

	@Override
	public void onClick(View v) {
	    TextView accountName = (TextView) mView.findViewById(R.id.accountname);
	    Dialog status = new ChangeStatus(Login.this, accountName.getText().toString(), mView).create();
	    status.show();
	}
    }

    /**
     * Event simple long click on item of the button of account list.
     */
    private class BeemConnectionOnLongClick implements android.view.View.OnLongClickListener {
	private View mView;

	/**
	 * Constructor.
	 */
	public BeemConnectionOnLongClick(View v) {
	    mView = v;
	}

	@Override
	public boolean onLongClick(View v) {
	    TextView accountName = (TextView) mView.findViewById(R.id.accountname);
	    Intent i = new Intent(Login.this, ChangeStatus.class);
	    i.putExtra("beem_account", accountName.getText());
	    startActivity(i);
	    return true;
	}
    }

    /**
     * Event simple click on item of the account list.
     */
    private class BeemAccountListOnClick implements OnItemClickListener {
	/**
	 * Constructor.
	 */
	public BeemAccountListOnClick() {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
	    Intent i = new Intent(Login.this, ContactList.class);
	    TextView accountName = (TextView) v.findViewById(R.id.accountname);
	    i.putExtra(BeemIntent.EXTRA_ACCOUNT, accountName.getText());
	    startActivity(i);
	}
    }

    /**
     * Event receive from service.
     */
    private class BeemBroadcastReceiver extends BroadcastReceiver {

	/**
	 * Constructor.
	 */
	public BeemBroadcastReceiver() {

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
	    String action = intent.getAction();
	    String account = intent.getExtras().getString(BeemIntent.EXTRA_ACCOUNT);
	    int hash = account.hashCode();
	    if (hash < 0)
		hash = hash * -1;

	    View v = findViewById(hash);
	    TextView text = (TextView) v.findViewById(R.id.accountstatus);
	    ImageButton logo = (ImageButton) v.findViewById(R.id.loginanim_logo_anim);

	    if (BeemIntent.ACTION_CONNECTED.equals(action)) {
		if (text != null)
		    text.setText(R.string.contact_status_msg_available);
		if (logo != null) {
		    logo.setImageResource(R.drawable.beem_launcher_icon_color);
		    logo.clearAnimation();
		}
	    } else if (BeemIntent.ACTION_DISCONNECTED.equals(action)) {
		String message = intent.getExtras().getString(BeemIntent.EXTRA_MESSAGE);
		if (text != null)
		    text.setText(message);
		if (logo != null) {
		    logo.setImageResource(R.drawable.beem_launcher_icon_silver);
		    logo.clearAnimation();
		}
	    }
	}

    }
}
