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 TemperatureConverterActivity extends Activity {

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

        Button fahrButton = (Button) findViewById(R.id.fahrButton);
        Button celButton = (Button) findViewById(R.id.celsiusButton);

        fahrButton.setOnClickListener(new FahrToCelListener());
        celButton.setOnClickListener(new CelToFahrListener());

        if (getResources().getBoolean(R.bool.use_initial_temp)) {
            EditText temperature = 
                    (EditText) findViewById(R.id.temperature);
            temperature.setText(R.integer.initial_temp);
        }
    }

    class FahrToCelListener implements View.OnClickListener {
        public void onClick(View view) {
            EditText temperature = 
                    (EditText) findViewById(R.id.temperature);
            TextView result = (TextView) findViewById(R.id.result);
            try {
                String tempStr = temperature.getText().toString();
                double f = Double.parseDouble(tempStr);
                double c = (5.0 / 9.0) * (f - 32);

                Resources res = getResources();
                String f2c = res.getString(R.string.f2c_result, f ,c);
                result.setText(f2c);
            }
            catch (NumberFormatException nfe) {
                result.setText(getString(R.string.error));
            }
        }
    }

    class CelToFahrListener implements View.OnClickListener {
        public void onClick(View view) {
            EditText temperature = 
                    (EditText) findViewById(R.id.temperature);
            TextView result = (TextView) findViewById(R.id.result);
            try {
                String tempStr = temperature.getText().toString();
                double c = Double.parseDouble(tempStr);
                double f = (9.0 / 5.0) * c + 32;

                Resources res = getResources();
                String c2f = res.getString(R.string.c2f_result, c, f);
                result.setText(c2f);
            }
            catch (NumberFormatException nfe) {
                result.setText(getString(R.string.error));
            }
        }
    }
}