package se.kth.anderslm.guessfinal;

import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView textOutput;
	private Chronometer stopWatch;
	private EditText textInput;
	private Button submitButton;
	private Button newGameButton;

	private GuessMyWordModel guessModel;

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

		textInput = (EditText) findViewById(R.id.editText1);
		textOutput = (TextView) findViewById(R.id.textView1);
		stopWatch = (Chronometer) findViewById(R.id.chronometer1);
		submitButton = (Button) findViewById(R.id.button1);
		submitButton.setOnClickListener(new SubmitClickListener());
		newGameButton = (Button) findViewById(R.id.button2);
		newGameButton.setOnClickListener(new NewGameClickListener());

		guessModel = new GuessMyWordModel();
	}

	private class SubmitClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// Define what to do when the user selects the "Submit" button
			String inputString = textInput.getText().toString();
			if (inputString.length() > 0) {
				char guess = inputString.charAt(0);
				guessModel.handleGuess(guess);

				int n = guessModel.getNoOfGuesses();
				String soFar = guessModel.getGuessSoFar();
				textOutput.setText(soFar + ", Guesses = " + n);
				textInput.selectAll();
				if (guessModel.isSolved()) {
					showToast("GONGRATULATIONS!!!");
					stopWatch.stop();
				}
			} else {
				showToast("Please enter a letter!");
			}
		}
	}

	private class NewGameClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// Define what to do when the user selects the "New game" button
			guessModel.reset();
			String soFar = guessModel.getGuessSoFar();
			textOutput.setText("The word: " + soFar);
			stopWatch.setBase(SystemClock.elapsedRealtime());
			stopWatch.start();
		}
	}

	private void showToast(String message) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}
