package com.example.countdown;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class CountdownActivity extends Activity {
    private static final int MILLISECONDS_PER_DAY =
            24 * 60 * 60 * 1000;

    private String eventName = "Christmas";
    private Calendar eventCalendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // default to this year's Christmas
        int thisYear = Calendar.getInstance().get(Calendar.YEAR);
        eventCalendar =
                new GregorianCalendar(thisYear, Calendar.DECEMBER, 25);
        setText();
    }

    private void setText() {
        int daysUntilEvent = getDaysUntilEvent(eventCalendar);
        TextView text = (TextView) findViewById(R.id.countdown);

        if (daysUntilEvent == 1) {
            text.setText(getString(R.string.countdownSingular,
                    daysUntilEvent, eventName));
        }
        else {
            text.setText(getString(R.string.countdown,
                    daysUntilEvent, eventName));
        }
    }

    private int getDaysUntilEvent(Calendar event) {
        GregorianCalendar nowCal = new GregorianCalendar();
        long eventTimeStamp = event.getTime().getTime();
        long nowTimeStamp = nowCal.getTime().getTime();
        return (int) Math.ceil((eventTimeStamp - nowTimeStamp)
                / (double) MILLISECONDS_PER_DAY);
    }
}