package com.example.converter;

import java.text.NumberFormat;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DistanceConverterActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.distance);

        Button milesButton = (Button) findViewById(R.id.milesButton);
        Button kmButton = (Button) findViewById(R.id.kmButton);

        // Register the listener with both buttons
        milesButton.setOnClickListener(new MilesToKmListener());
        kmButton.setOnClickListener(new KmToMilesListener());
    }

    class MilesToKmListener implements View.OnClickListener {
        public void onClick(View view) {
            EditText distance = (EditText) findViewById(R.id.distance);
            TextView result = (TextView) findViewById(R.id.result);

            // Retrieve the distance to convert from
            String distanceStr = distance.getText().toString();

            try {
                double m = Double.parseDouble(distanceStr);
                double km = m * 1.609;
                String kmStr = NumberFormat.getInstance().format(km);
                result.setText(distanceStr + " miles is " + kmStr
                        + " kilometers");
            }
            catch (NumberFormatException nfe) {
                result.setText("Please enter a number");
            }
        }
    }

    class KmToMilesListener implements View.OnClickListener {
        public void onClick(View view) {
            EditText distance = (EditText) findViewById(R.id.distance);
            TextView result = (TextView) findViewById(R.id.result);

            // Retrieve the distance to convert from
            String distanceStr = distance.getText().toString();

            try {
                double km = Double.parseDouble(distanceStr);
                double m = km / 1.609;
                String mStr = NumberFormat.getInstance().format(m);
                result.setText(distanceStr + " kilometers is " + mStr
                        + " miles");
            }
            catch (NumberFormatException nfe) {
                result.setText("Please enter a number");
            }
        }
    }
}