package kimiko.coreen.app;

import java.util.Random;

import kimiko.coreen.app.data.base.MotDAO;
import kimiko.coreen.app.data.mots.Mot;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends Activity {
	private final static Random random = new Random();
	private TextView word;
	private RadioButton[] radio = new RadioButton[3];
	private int r;
	private double correct=1, incorrect=0;
	private RatingBar rating;
	private MotDAO motDAO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_quiz);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		this.word = (TextView) findViewById(R.id.quizWord);
		this.radio[0] = (RadioButton) findViewById(R.id.radio0);
		this.radio[1] = (RadioButton) findViewById(R.id.radio1);
		this.radio[2] = (RadioButton) findViewById(R.id.radio2);
		this.rating = (RatingBar) findViewById(R.id.ratingBar1);
		rating.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return true;
			}
	    });
		
		motDAO = new MotDAO(this);
		motDAO.open();
		
		this.newWord();
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_quiz, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_bon:
			if(this.radio[r].isChecked())
			{
				Toast.makeText(this, getResources().getString(R.string.quiz_correct), Toast.LENGTH_SHORT).show();
				this.correct++;
				this.newWord();
			}
			else
			{
				Toast.makeText(this, getResources().getString(R.string.quiz_incorrect), Toast.LENGTH_SHORT).show();
				this.incorrect++;
				this.tryAnwser();
			}
			return true;
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private void tryAnwser() {
		this.rating.setProgress((int)(this.rating.getMax()*(correct/(incorrect+correct))));
	}
	private void newWord() {
		Mot w1, w2, w3;
		
		w1 = motDAO.random();
		w2 = motDAO.random();
		w3 = motDAO.random();
		this.word.setText(w1.getHangeul());
		this.r = random.nextInt(3);

		this.radio[r].setText(w1.getTraduction());
		this.radio[(r+1)%3].setText(w2.getTraduction());
		this.radio[(r+2)%3].setText(w3.getTraduction());
		
		this.tryAnwser();
	}
	
	@Override
	public void onDestroy() {
		motDAO.close();
		super.onDestroy();
	}
}
