package fr.univ.amu.iut.iutinfogame.salaun;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import fr.univ.amu.iut.iutinfogame.R;

public class SalaunActivity extends ActionBarActivity {

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

		setContentView(R.layout.activity_salaun);
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		private final static int TIMER = 10;

		private TextView tvCounter, tvTime;
		private int counter = 0;
		private int time = 0;
		private Timer myTimer;
		private boolean timeUp = false;

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_salaun, container, false);

			tvCounter = (TextView) rootView.findViewById(R.id.fragment_salaun_textView_counter);
			tvTime = (TextView) rootView.findViewById(R.id.fragment_salaun_textView_time);

			rootView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(!timeUp){
						counter++;
						tvCounter.setText(Integer.toString(counter));
					}
				}
			});

			time = TIMER;
			myTimer = new Timer();
			myTimer.schedule(new TimerTask() {			
				@Override
				public void run() {
					TimerMethod();
				}

			}, 0, 1000);

			return rootView;
		}

		private void TimerMethod() {
			//This method is called directly by the timer
			//and runs in the same thread as the timer.

			//We call the method that will work with the UI
			//through the runOnUiThread method.
			getActivity().runOnUiThread(Timer_Tick);
		}


		private Runnable Timer_Tick = new Runnable() {
			public void run() {
				time--;
				//This method runs in the same thread as the UI.    	       
				tvTime.setText( Integer.toString(time) );
				if(time <= 0){
					myTimer.cancel();
					timeUp = true;
				}
			}
		};
	}
}
