package com.example.converter;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DistanceConverterActivity extends MenuActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.distance);

		View image = findViewById(R.id.distanceImage);
        registerForContextMenu(image);

        final Button milesButton = (Button) findViewById(R.id.milesButton);
		final Button kmButton = (Button) findViewById(R.id.kmButton);
		final EditText distanceEditText = (EditText) findViewById(R.id.distance);
		final TextView result = (TextView) findViewById(R.id.result);

		OnClickListener listener = new OnClickListener() {
			public void onClick(View view) {
				Resources res = getResources();
				try {
					double dist = Double.parseDouble(distanceEditText.getText()
							.toString());

					if (((Button) view).getText().equals(milesButton.getText())) {
						String m2k = res.getString(R.string.m2k_result);
						double km = dist * 1.609;
						result.setText(String.format(m2k, dist, km));
					} else if (((Button) view).getText().equals(
							kmButton.getText())) {
						String k2m = res.getString(R.string.k2m_result);
						double m = dist / 1.609;
						result.setText(String.format(k2m, dist, m));
					}
				} catch (NumberFormatException nfe) {
					result.setText(getString(R.string.error));
				}
			}
		};

		milesButton.setOnClickListener(listener);
		kmButton.setOnClickListener(listener);

		if (getResources().getBoolean(R.bool.use_initial_distance)) {
			distanceEditText.setText(R.integer.initial_distance);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		menu.findItem(R.id.distance_converter).setEnabled(false);
		return true;
	}

	@Override
	protected void showContextSensitiveHelpDialog() {
		showDistanceHelpDialog();
	}
}