<commit_before>/*

Copyright 2014 Profesores y alumnos de la asignatura Informática Móvil de la EPI de Gijón

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package es.uniovi.imovil.fcrtrainer.digitalinformation;

import java.util.Date;
import java.util.Locale;
import java.util.Random;

import org.json.JSONException;

import es.uniovi.imovil.fcrtrainer.BaseExerciseFragment;
import es.uniovi.imovil.fcrtrainer.R;
import es.uniovi.imovil.fcrtrainer.highscores.HighscoreManager;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public abstract class BaseNumericalExerciseFragment extends
		BaseExerciseFragment {
	private static final int GAMEMODE_MAXQUESTIONS = 5;

	private static final String STATE_DIRECT_CONVERSION = "mDirectConversion";
	private static final String STATE_NUMBER_TO_CONVERT = "mNumberToConvert";

	private EditText mAnswerTextView;
	private Button mCheckButton;
	private Button mChangeDirectionButton;
	private Button mSolutionButton;
	private TextView mNumberToConvertTextView;
	private TextView mTitleTextView;
	protected String mNumberToConvert;
	private int mQuestionCounter = 0;
	private int mPoints = 0;

	protected Random mRandomGenerator;
	protected boolean mDirectConversion = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView;
		rootView = inflater.inflate(R.layout.fragment_numerical_exercise,
				container, false);

		mAnswerTextView = (EditText) rootView.findViewById(R.id.answer);
		mChangeDirectionButton = (Button) rootView.findViewById(R.id.change);
		mSolutionButton = (Button) rootView.findViewById(R.id.seesolution);
		mCheckButton = (Button) rootView.findViewById(R.id.checkbutton);
		mNumberToConvertTextView = (TextView) rootView
				.findViewById(R.id.numbertoconvert);
		mTitleTextView = (TextView) rootView.findViewById(R.id.exercisetitle);
		mRandomGenerator = new Random();

		mAnswerTextView.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (EditorInfo.IME_ACTION_DONE == actionId) {
					checkSolution(mAnswerTextView.getEditableText().toString()
							.trim().toLowerCase(Locale.US));
				}
				return false;
			}
		});

		// Set the focus on the edit text and show the keyboard
		if (mAnswerTextView.requestFocus()) {
			getActivity().getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		}

		mCheckButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				checkSolution(mAnswerTextView.getEditableText().toString()
						.trim().toLowerCase(Locale.US));
			}
		});

		mChangeDirectionButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDirectConversion ^= true;
				setKeyboardLayout();
				newQuestion();
			}
		});

		mSolutionButton.setOnClickListener(new OnClickListener() {

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

		return rootView;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (savedInstanceState != null) {
			mDirectConversion = savedInstanceState
					.getBoolean(STATE_DIRECT_CONVERSION);
			mNumberToConvert = savedInstanceState
					.getString(STATE_NUMBER_TO_CONVERT);
		} else {
			generateRandomQuestion();
		}

		updateUI();
		setKeyboardLayout();
	}

	private void setKeyboardLayout() {
		if (!isResultNumeric()) {
			mAnswerTextView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
		} else {
			// setInputType cannot be used because it doesn't allow the sign
			mAnswerTextView.setRawInputType(InputType.TYPE_CLASS_NUMBER
					| InputType.TYPE_NUMBER_FLAG_SIGNED);
		}
	}

	private void setTitle() {
		mTitleTextView.setText(titleString());
	}

	private void generateRandomQuestion() {
		mNumberToConvert = generateRandomNumber();
	}

	protected int numberOfBits() {
		return level().numberOfBits();
	}
	
	private void updateUI() {
		mNumberToConvertTextView.setText(mNumberToConvert);
		setTitle();
	}

	/**
	 * Checks if the answer is correct. If the game mode is selected checks for
	 * the number of questions that already has been asked, in case that number
	 * is equal to the max number allowed calls endGame(). Also it adds a point
	 * for each correct answer in that mode.
	 * 
	 * @param answer
	 *            the user input
	 */
	private void checkSolution(String answer) {
		if (isCorrect(answer)) {
			showAnimationAnswer(true);
			if (mIsPlaying) {
				handleCorrectAnswer();
			}
			newQuestion();
		} else
			showAnimationAnswer(false);
	}

	private void newQuestion() {
		clearAnswer();
		generateRandomQuestion();
		updateUI();
	}

	private void showSolution() {
		mAnswerTextView.setText(obtainSolution());
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(STATE_DIRECT_CONVERSION, mDirectConversion);
		outState.putString(STATE_NUMBER_TO_CONVERT, mNumberToConvert);
	}

	/**
	 * Prepares the layout for the training and game mode.
	 * 
	 * @param training
	 *            true if the change is to the training mode
	 */
	private void setTrainingMode(boolean training) {
		if (training) {
			mIsPlaying = false;
			mSolutionButton.setVisibility(View.VISIBLE);
		} else {
			mIsPlaying = true;
			resetGameState();
			mSolutionButton.setVisibility(View.GONE);
		}
		clearAnswer();
	}

	/**
	 * Updates the game stats and if all the questions have been asked it calls
	 * the endGame() method.
	 */
	private void handleCorrectAnswer() {
		mPoints += pointsForCorrectAnswer();
		updateScore(mPoints);

		mQuestionCounter++;
		if (mQuestionCounter == GAMEMODE_MAXQUESTIONS) {
			endGame();
		}
	}

	private void resetGameState() {<commit_msg>Ocultar el botón de cambio de sentido en el modo juego<commit_after>/*

Copyright 2014 Profesores y alumnos de la asignatura Informática Móvil de la EPI de Gijón

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */

package es.uniovi.imovil.fcrtrainer.digitalinformation;

import java.util.Date;
import java.util.Locale;
import java.util.Random;

import org.json.JSONException;

import es.uniovi.imovil.fcrtrainer.BaseExerciseFragment;
import es.uniovi.imovil.fcrtrainer.R;
import es.uniovi.imovil.fcrtrainer.highscores.HighscoreManager;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public abstract class BaseNumericalExerciseFragment extends
		BaseExerciseFragment {
	private static final int GAMEMODE_MAXQUESTIONS = 5;

	private static final String STATE_DIRECT_CONVERSION = "mDirectConversion";
	private static final String STATE_NUMBER_TO_CONVERT = "mNumberToConvert";

	private EditText mAnswerTextView;
	private Button mCheckButton;
	private Button mChangeDirectionButton;
	private Button mSolutionButton;
	private TextView mNumberToConvertTextView;
	private TextView mTitleTextView;
	protected String mNumberToConvert;
	private int mQuestionCounter = 0;
	private int mPoints = 0;

	protected Random mRandomGenerator;
	protected boolean mDirectConversion = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView;
		rootView = inflater.inflate(R.layout.fragment_numerical_exercise,
				container, false);

		mAnswerTextView = (EditText) rootView.findViewById(R.id.answer);
		mChangeDirectionButton = (Button) rootView.findViewById(R.id.change);
		mSolutionButton = (Button) rootView.findViewById(R.id.seesolution);
		mCheckButton = (Button) rootView.findViewById(R.id.checkbutton);
		mNumberToConvertTextView = (TextView) rootView
				.findViewById(R.id.numbertoconvert);
		mTitleTextView = (TextView) rootView.findViewById(R.id.exercisetitle);
		mRandomGenerator = new Random();

		mAnswerTextView.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (EditorInfo.IME_ACTION_DONE == actionId) {
					checkSolution(mAnswerTextView.getEditableText().toString()
							.trim().toLowerCase(Locale.US));
				}
				return false;
			}
		});

		// Set the focus on the edit text and show the keyboard
		if (mAnswerTextView.requestFocus()) {
			getActivity().getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		}

		mCheckButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				checkSolution(mAnswerTextView.getEditableText().toString()
						.trim().toLowerCase(Locale.US));
			}
		});

		mChangeDirectionButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mDirectConversion ^= true;
				setKeyboardLayout();
				newQuestion();
			}
		});

		mSolutionButton.setOnClickListener(new OnClickListener() {

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

		return rootView;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (savedInstanceState != null) {
			mDirectConversion = savedInstanceState
					.getBoolean(STATE_DIRECT_CONVERSION);
			mNumberToConvert = savedInstanceState
					.getString(STATE_NUMBER_TO_CONVERT);
		} else {
			generateRandomQuestion();
		}

		updateUI();
		setKeyboardLayout();
	}

	private void setKeyboardLayout() {
		if (!isResultNumeric()) {
			mAnswerTextView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
		} else {
			// setInputType cannot be used because it doesn't allow the sign
			mAnswerTextView.setRawInputType(InputType.TYPE_CLASS_NUMBER
					| InputType.TYPE_NUMBER_FLAG_SIGNED);
		}
	}

	private void setTitle() {
		mTitleTextView.setText(titleString());
	}

	private void generateRandomQuestion() {
		mNumberToConvert = generateRandomNumber();
	}

	protected int numberOfBits() {
		return level().numberOfBits();
	}
	
	private void updateUI() {
		mNumberToConvertTextView.setText(mNumberToConvert);
		setTitle();
	}

	/**
	 * Checks if the answer is correct. If the game mode is selected checks for
	 * the number of questions that already has been asked, in case that number
	 * is equal to the max number allowed calls endGame(). Also it adds a point
	 * for each correct answer in that mode.
	 * 
	 * @param answer
	 *            the user input
	 */
	private void checkSolution(String answer) {
		if (isCorrect(answer)) {
			showAnimationAnswer(true);
			if (mIsPlaying) {
				handleCorrectAnswer();
			}
			newQuestion();
		} else
			showAnimationAnswer(false);
	}

	private void newQuestion() {
		clearAnswer();
		generateRandomQuestion();
		updateUI();
	}

	private void showSolution() {
		mAnswerTextView.setText(obtainSolution());
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(STATE_DIRECT_CONVERSION, mDirectConversion);
		outState.putString(STATE_NUMBER_TO_CONVERT, mNumberToConvert);
	}

	/**
	 * Prepares the layout for the training and game mode.
	 * 
	 * @param training
	 *            true if the change is to the training mode
	 */
	private void setTrainingMode(boolean training) {
		if (training) {
			mIsPlaying = false;
			mSolutionButton.setVisibility(View.VISIBLE);
			mChangeDirectionButton.setVisibility(View.VISIBLE);
		} else {
			mIsPlaying = true;
			resetGameState();
			mSolutionButton.setVisibility(View.GONE);
			mChangeDirectionButton.setVisibility(View.GONE);
		}
		clearAnswer();
	}

	/**
	 * Updates the game stats and if all the questions have been asked it calls
	 * the endGame() method.
	 */
	private void handleCorrectAnswer() {
		mPoints += pointsForCorrectAnswer();
		updateScore(mPoints);

		mQuestionCounter++;
		if (mQuestionCounter == GAMEMODE_MAXQUESTIONS) {
			endGame();
		}
	}

	private void resetGameState() {
{'fraction_non_alphanumeric': 0.08894334726827159, 'fraction_numerical': 0.0017298544039210033, 'mean_word_length': 4.6655777868517765, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '834290', 'n_tokens_mistral': 4585, 'n_tokens_neox': 3953, 'n_words': 1038}