package com.example.fideliza;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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 android.widget.Toast;

public class MainActivity extends Activity {
	private ImageView bMaps, bTarj;
	private ImageView logo;
	private TextView tmensaje;
	private MiThread thread;
	private Vector<String> mensajes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		bMaps = (ImageView) findViewById(R.id.tiendas);
		Animation animacioncfg = AnimationUtils.loadAnimation(this,
				R.anim.aparecer);
		bMaps.startAnimation(animacioncfg);
		bMaps.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				lanzarMaps(null);
			}
		});
		bTarj = (ImageView) findViewById(R.id.tarjeta);
		animacioncfg = AnimationUtils.loadAnimation(this, R.anim.aparecer_2);
		bTarj.startAnimation(animacioncfg);
		bTarj.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				lanzarTarj(null);
			}
		});

		logo = (ImageView) findViewById(R.id.imageView1);
		animacioncfg = AnimationUtils.loadAnimation(this, R.anim.giro_con_zoom);
		logo.startAnimation(animacioncfg);
		// leemos mensajes de publicidad y los mostramos
		mensajes = listaMensajes();
		if (mensajes.size() != 0) { // Si no hay mensajes a mostrar, no lanzamos
									// el thread (errores de conexión,.....)
			thread = new MiThread(mensajes); // Muestra los mensajes de forma
												// indefinida
			thread.start();
		}
	}

	public void lanzarMaps(View view) {
		Intent i = new Intent(this, IniciaMaps.class);
		startActivity(i);
	}

	public void lanzarTarj(View view) {
		Intent i = new Intent(this, Activar.class);
		startActivity(i);
	}

	public Vector<String> listaMensajes() {
		try {
			TareaLista tarea = new TareaLista();
			tarea.execute();
			return tarea.get(4, TimeUnit.SECONDS);
		} catch (TimeoutException e) {
			Toast.makeText(this, "Tiempo excedido al conectar",
					Toast.LENGTH_LONG).show();

		} catch (CancellationException e) {
			Toast.makeText(this, "Error al conectar con servidor",
					Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Toast.makeText(this, "Error con tarea asíncrona", Toast.LENGTH_LONG)
					.show();
		}
		return new Vector<String>();
	}

	private class TareaLista extends AsyncTask<Void, Void, Vector<String>> {
		@Override
		protected Vector<String> doInBackground(Void... arg0) {
			Vector<String> result = new Vector<String>();
			try {
				URL url = new URL("http://www.piavant.es/mensaje.php?cod=pi");
				HttpURLConnection conexion = (HttpURLConnection) url
						.openConnection();
				if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(conexion.getInputStream()));
					String linea = reader.readLine();
					while (!linea.equals("")) {
						result.add(linea);
						linea = reader.readLine();
					}
					reader.close();
					return result;
				} else {
					Log.e("Fideliza", conexion.getResponseMessage());
					cancel(true);
					return result;
				}
			} catch (Exception e) {
				Log.e("Fideliza", e.getMessage(), e);
				cancel(true);
				return result;
			}
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mensajes.size() != 0) { // El thread habrá sido lanzado --->
									// pausarlo
			thread.pausar();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mensajes.size() != 0) { // El thread habrá sido lanzado --->
									// reanudarlo
			thread.reanudar();
		}
	}

	class MiThread extends Thread {
		private Vector<String> msg;
		
		private boolean pausa, corriendo;

		public synchronized void pausar() {
			pausa = true;
		}

		public synchronized void reanudar() {
			pausa = false;
			notify();
		}

		public void detener() {
			corriendo = false;
			if (pausa)
				reanudar();
		}

		
		public MiThread(Vector<String> msg) {
			this.msg = msg;

		}

		class MyRunnable implements Runnable {
			private final int indice;

			public MyRunnable(final int indice) {
				this.indice = indice;
			}

			public void run() {
				tmensaje.setText(msg.get(indice));
			}
		}

		@Override
		public void run() {
			// en msg tenemos los mensajes a mostrar
			tmensaje = (TextView) findViewById(R.id.mensaje);
			corriendo = true;
			while (corriendo) {
				for (int i = 0; i < msg.size(); i++) {
					MyRunnable myRunnable = new MyRunnable(i);
					runOnUiThread(myRunnable);

					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (this) {
						while (pausa) {
							try {
								wait();
							} catch (Exception e) {
							}
						}
					}

				}

			}
		}
	}
}
