package com.ramos.munoz.tesis;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class VehiculoActivity extends Activity {

    private static ArrayList<Vehiculo> vehiculos;
    private VehiculoAdaptadorLw adaptadorVehiculo = null;
    private ListView lv;
    private Context contexto = this;
    private int numVehiculos;
    private Button btnTodos;
    private boolean todos = false;
    private boolean mostrandoMensaje = false;
    private LinearLayout llActivity;

    public static final int RESPUESTA_VEHICULOS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.vehiculo_activity);
	numVehiculos = 0;
	inicializarComponentes();

    }

    private void inicializarComponentes() {
	lv = (ListView) findViewById(R.id.lvVehiculos);
	vehiculos = new ArrayList<Vehiculo>();
	adaptadorVehiculo = new VehiculoAdaptadorLw(this, R.layout.vehiculo_listview, vehiculos);
	iniciarLista();

    }

    private void iniciarLista() {

	CargarVehiculosTask cargarVehiculosTask = new CargarVehiculosTask();
	cargarVehiculosTask.execute();

    }

    protected void mostrarDetalle(int pos) {
	Intent detalle = new Intent(contexto, VehiculoDetalle.class);
	Vehiculo ve = vehiculos.get(pos);
	detalle.putExtra("marca", ve.getMarca());
	detalle.putExtra("modelo", ve.getModelo());
	detalle.putExtra("patente", ve.getPatente());
	detalle.putExtra("carroceria", ve.getCarroceriaNombre());
	detalle.putExtra("id", ve.getId());
	startActivityForResult(detalle, RESPUESTA_VEHICULOS);
    }

    @Override
    protected void onRestart() {
	super.onRestart();
    }

    @Override
    protected void onPause() {
	super.onPause();
	removerMensaje();

    }

    private void removerMensaje() {
	if (mostrandoMensaje) {
	    llActivity.removeViewAt(2);
	    llActivity.removeViewAt(0);
	    mostrandoMensaje = false;
	}
    }

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

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	super.onMenuItemSelected(featureId, item);
	switch (item.getItemId()) {
	    case R.id.menuAgregarVehiculo:
		iniciarActivity(VehiculoAgregar.class);
		break;
	    case R.id.menuEliminarVehiculo:
		mostrarSeleccion();
		break;
	}
	return true;
    }

    private void mostrarSeleccion() {
	llActivity = (LinearLayout) findViewById(R.id.llVehiculo);
	View v = this.getLayoutInflater().inflate(R.layout.vehiculo_mensaje_eliminar, null);
	Button btnCancelar = (Button) v.findViewById(R.id.btnCancelar);

	btnTodos = (Button) v.findViewById(R.id.btnSeleccionarTodos);
	Button btnEliminar = (Button) v.findViewById(R.id.btnEliminar);

	for (int i = 0; i < lv.getChildCount(); i++) {
	    lv.setOnItemClickListener(null);
	    RelativeLayout rl = (RelativeLayout) lv.getChildAt(i);
	    CheckBox chk = (CheckBox) rl.findViewById(R.id.chkFila);
	    chk.setVisibility(1);

	    ImageButton detalle = (ImageButton) rl.findViewById(R.id.btnDetalleEstacionamiento);
	    detalle.setVisibility(View.INVISIBLE);
	}

	RelativeLayout rlHead = (RelativeLayout) v.findViewById(R.id.rlTituloMensaje);
	RelativeLayout rlPie = (RelativeLayout) v.findViewById(R.id.rlPieMensaje);
	((ViewGroup) rlPie.getParent()).removeView(rlPie);
	((ViewGroup) rlHead.getParent()).removeView(rlHead);
	llActivity.addView(rlPie, 1);
	llActivity.addView(rlHead, 0);
	mostrandoMensaje = true;

	btnCancelar.setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		removerMensaje();
		for (int i = 0; i < lv.getChildCount(); i++) {
		    RelativeLayout rl = (RelativeLayout) lv.getChildAt(i);
		    CheckBox chk = (CheckBox) rl.findViewById(R.id.chkFila);
		    chk.setVisibility(View.INVISIBLE);
		    ImageButton detalle = (ImageButton) rl.findViewById(R.id.btnDetalleEstacionamiento);
		    detalle.setVisibility(View.VISIBLE);
		}
	    }
	});

	btnTodos.setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		for (int i = 0; i < lv.getChildCount(); i++) {
		    RelativeLayout rl = (RelativeLayout) lv.getChildAt(i);
		    CheckBox chk = (CheckBox) rl.findViewById(R.id.chkFila);

		    if (todos) {
			chk.setChecked(false);

			vehiculos.get(i).setSeleccionado(false);
		    } else {
			chk.setChecked(true);
			vehiculos.get(i).setSeleccionado(true);
		    }
		}
		todos = !todos;
		adaptadorVehiculo.notifyDataSetChanged();
	    }
	});

	btnEliminar.setOnClickListener(new OnClickListener() {

	    public void onClick(View arg0) {

		eliminarVehiculo();
	    }
	});
    }

    public static void marcarVehiculoParaEliminar(int pos, Boolean seleccion) {
	vehiculos.get(pos).setSeleccionado(seleccion);
    }

    private void eliminarVehiculo() {
	EliminarVehiculoTask eliminarVehiculoTask = new EliminarVehiculoTask();
	eliminarVehiculoTask.execute();
    }

    private void iniciarActivity(Class<?> c) {
	Intent activity = new Intent(this, c);
	startActivityForResult(activity, RESPUESTA_VEHICULOS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == RESPUESTA_VEHICULOS) {
	    if (resultCode == RESPUESTA_VEHICULOS) {
		iniciarLista();
	    }
	}
    }

    class VehiculoAdaptadorLw extends ArrayAdapter<Vehiculo> {

	private Context contexto;
	private int layout;
	private VehiculoHolderLw holder;
	private ArrayList<Vehiculo> vehiculos;
	private Vehiculo v;

	public VehiculoAdaptadorLw(Context context, int layout, ArrayList<Vehiculo> vehiculos) {
	    super(context, layout, vehiculos);
	    this.layout = layout;
	    this.contexto = context;
	    this.vehiculos = vehiculos;
	}

	@Override
	public View getView(final int pos, View view, ViewGroup parent) {
	    View fila = view;
	    holder = new VehiculoHolderLw();

	    LayoutInflater inflater = (LayoutInflater) contexto.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    fila = inflater.inflate(layout, parent, false);
	    holder = new VehiculoHolderLw();
	    holder.sel = (CheckBox) fila.findViewById(R.id.chkFila);
	    holder.detalle = (ImageButton) fila.findViewById(R.id.btnDetalleEstacionamiento);
	 
	    holder.sel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

		public void onCheckedChanged(CompoundButton view, boolean isChecked) {
		    VehiculoActivity.marcarVehiculoParaEliminar(pos, isChecked);
		}
	    });

	    holder.detalle.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    mostrarDetalle(pos);
		}
	    });

	    holder.campo = (TextView) fila.findViewById(R.id.txtFila);
	    v = vehiculos.get(pos);
	    holder.campo.setText(v.getPatente());

	    return fila;
	}
    }

    class VehiculoHolderLw {
	TextView campo;
	CheckBox sel;
	ImageButton detalle;
    }

    class EliminarVehiculoTask extends AsyncTask<Object, Integer, Boolean> {
	private ProgressDialog barraEstado;

	@Override
	protected Boolean doInBackground(Object... params) {
	    return Vehiculo.eliminarVehiculo(vehiculos);
	}

	protected void onPreExecute() {
	    barraEstado = new ProgressDialog(VehiculoActivity.this);
	    barraEstado.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    barraEstado.setMessage(getString(R.string.borrandoVehiculos));
	    barraEstado.show();
	    barraEstado.setCanceledOnTouchOutside(false);
	}

	@Override
	protected void onPostExecute(Boolean resp) {
	    if (resp) {
		Toast.makeText(contexto, getString(R.string.borrandoVehiculos), Toast.LENGTH_SHORT).show();
		adaptadorVehiculo = null;
		vehiculos = new ArrayList<Vehiculo>();
		numVehiculos = 0;
		removerMensaje();
		iniciarLista();

	    } else {
		Toast.makeText(contexto, getString(R.string.borrarFail), Toast.LENGTH_SHORT).show();
	    }
	    barraEstado.dismiss();
	}

    }

    class CargarVehiculosTask extends AsyncTask<Object, Integer, ArrayList<Vehiculo>> {
	private ProgressDialog barraEstado;

	@Override
	protected ArrayList<Vehiculo> doInBackground(Object... params) {
	    if (adaptadorVehiculo == null) {
		adaptadorVehiculo = new VehiculoAdaptadorLw(VehiculoActivity.this, R.layout.vehiculo_listview, vehiculos);
		numVehiculos = 0;
	    }
	    vehiculos = Usuario.cargarVehiculos();
	    return null;
	}

	protected void onPreExecute() {
	    barraEstado = new ProgressDialog(VehiculoActivity.this);
	    barraEstado.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    barraEstado.setMessage(getString(R.string.cargandoVehiculos));
	    barraEstado.show();
	    barraEstado.setCanceledOnTouchOutside(false);
	}

	@Override
	protected void onPostExecute(ArrayList<Vehiculo> result) {
	    if (numVehiculos < vehiculos.size()) {
		for (int i = numVehiculos; i < vehiculos.size(); i++) {
		    adaptadorVehiculo.add(vehiculos.get(i));
		    numVehiculos++;
		}
		adaptadorVehiculo.notifyDataSetChanged();
		lv.setAdapter(adaptadorVehiculo);

	    }
	    barraEstado.dismiss();
	}

    }

}
