package com.example.tips;

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

public class TipCalculatorActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button calculate = (Button) findViewById(R.id.calculate);
        calculate.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                EditText billAmountEditText =
                        (EditText) findViewById(R.id.billAmount);
                EditText percentEditText =
                        (EditText) findViewById(R.id.percent);
                TextView tipAmountTextView =
                        (TextView) findViewById(R.id.tipAmount);
                TextView totalBillTextView =
                        (TextView) findViewById(R.id.totalBill);
                Resources res = getResources();

                try {
                    float billAmount =
                            Float.parseFloat(billAmountEditText
                                    .getText().toString());
                    float tipPercent =
                            Float.parseFloat(percentEditText
                                    .getText().toString());
                    tipPercent = tipPercent / 100;
                    float tip = billAmount * tipPercent;
                    float total = billAmount + tip;

                    String tipLabel =
                            res.getString(R.string.tip_amount_label2);
                    String totalLabel =
                            res.getString(R.string.total_bill_label2);
                    tipAmountTextView.setText(String.format(tipLabel,
                            tip));
                    totalBillTextView.setText(String.format(
                            totalLabel, total));
                }
                catch (NumberFormatException e) {
                    tipAmountTextView
                            .setText(R.string.tip_amount_label);
                    totalBillTextView
                            .setText(R.string.total_bill_label);
                }
            }
        });
    }
}