package com.ramos.munoz.tesis;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends AccountAuthenticatorActivity implements OnClickListener {

    public static final String PARAM_AUTHOKEN_TYPE = "authtokenType";
    private String usuario;
    private String contrasena;
    private SharedPreferences prefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.login_activity);
	inicializarComponentes();
    }

    private void inicializarComponentes() {
	Button botonIngresar = (Button) findViewById(R.id.btnLogin);
	Button botonRegistrarse = (Button) findViewById(R.id.btnRegistrarse);
	botonIngresar.setOnClickListener(this);
	botonRegistrarse.setOnClickListener(this);
    }

    private void intentarIngresar(String usuario, String contrasena) {

	String[] datos = { usuario, contrasena };
	LoginAsincrono logTask = new LoginAsincrono();
	logTask.execute(datos);
    }

    // EVENTOS
    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	    case R.id.btnLogin:

		EditText txtUsuario = (EditText) findViewById(R.id.txtUsuario);
		EditText txtPass = (EditText) findViewById(R.id.txtPass);
		if (Validacion.isVacio(txtUsuario)) {
		    Toast.makeText(this, "Ingrese nombre de usuario", Toast.LENGTH_SHORT).show();
		    break;
		}
		if (Validacion.isVacio(txtPass)) {
		    Toast.makeText(this, "Ingrese la contraseņa", Toast.LENGTH_SHORT).show();
		    break;
		}
		usuario = txtUsuario.getText().toString();
		contrasena = txtPass.getText().toString();
		intentarIngresar(usuario, contrasena);
		break;
	    case R.id.btnRegistrarse:
		try {
		    Intent intent = new Intent(this, RegistroDeUsuario.class);
		    startActivity(intent);
		} catch (Exception e) {
		    e.printStackTrace();
		    Log.e("Login", "Error: " + e.getMessage());
		}
		break;
	}
    }

    // TASKS
    class LoginAsincrono extends AsyncTask<String, Integer, Boolean> {
	private ProgressDialog barraEstado;

	@Override
	protected Boolean doInBackground(String... params) {
	    String usuario = params[0];
	    String contrasena = params[1];
	    Usuario usuarioMovil = new Usuario();
	    String respuesta = usuarioMovil.ingresar(usuario, contrasena);
	    if (respuesta == "bien") {

		return true;

	    } else {
		return false;
	    }
	}

	@Override
	protected void onPostExecute(Boolean resp) {
	    super.onPostExecute(resp);
	    if (resp) {
		Bundle extras = getIntent().getExtras();

		String accountType = Constantes.AUTHTOKEN_TYPE;

		Account account = new Account(usuario, Constantes.AUTHTOKEN_TYPE);
		AccountManager am = AccountManager.get(LoginActivity.this);
		boolean accountCreated = am.addAccountExplicitly(account, contrasena, null);

		if (accountCreated) {
		    Intent result = new Intent();
		    if (extras != null) {

			result.putExtra(AccountManager.KEY_ACCOUNT_NAME, usuario);
			result.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
			result.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);

		    } else {
			Intent intent = new Intent(LoginActivity.this, MapaActivity.class);
			startActivity(intent);
		    }
		    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		    result = new Intent(LoginActivity.this, LauncherActivity.class);
		    SharedPreferences.Editor editPrefs = prefs.edit();
		    editPrefs.putString("editUsuario", usuario);
		    editPrefs.putString("editPassword", contrasena);
		    Log.d("Usuario", usuario);
		    editPrefs.commit();
		    LoginActivity.this.setResult(RESULT_OK, result);
		    finish();
		}

	    }
	    if (barraEstado.isShowing()) {

		barraEstado.dismiss();
	    }

	}

	@Override
	protected void onPreExecute() {
	    barraEstado = new ProgressDialog(LoginActivity.this);
	    barraEstado.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    barraEstado.setMessage(getString(R.string.autenticando));
	    barraEstado.setCanceledOnTouchOutside(false);
	    barraEstado.show();
	    super.onPreExecute();
	}

    }
}
