package com.example.converter;

import android.app.Activity;
import android.content.res.Resources;
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());
        
        if (getResources().getBoolean(R.bool.use_initial_distance)) {
            EditText distance = (EditText) findViewById(R.id.distance);
            distance.setText(R.integer.initial_distance);
        }                   
    }

    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 {
                Resources res = getResources();
                double m = Double.parseDouble(distanceStr);
                double km = m * 1.609;
                String m2k = res.getString(R.string.m2k_result);
                result.setText(String.format(m2k, m, km));
            }
            catch (NumberFormatException nfe) {
                result.setText(getString(R.string.error));
            }
        }
    }

    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 {
                Resources res = getResources();
                double km = Double.parseDouble(distanceStr);
                double m = km / 1.609;
                String k2m = res.getString(R.string.k2m_result);
                result.setText(String.format(k2m, km, m));
            }
            catch (NumberFormatException nfe) {
                result.setText(getString(R.string.error));
            }
        }
    }
}