package com.example.scores.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.ListView;

import com.example.scores.R;
import com.example.scores.utilities.Score;
import com.example.scores.utilities.ScoreListAdapter;

public class DisplayScoresActivity extends Activity {
    private ScoreListAdapter adapter;
    private ArrayList<Parcelable> scores;
    private BroadcastReceiver scoreReceiver = new ScoresReceiver();
    private IntentFilter filter = new IntentFilter(
            "com.example.scores.BROADCAST");
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displayscores);

        // retrieve the data to load into the ListView from
        // the Intent as an extra
        Intent intent = getIntent();
        scores = intent.getParcelableArrayListExtra("Scores");

        adapter = new ScoreListAdapter(this, scores);
        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
    }
    
    // BroadcastReceiver to update the activity's ListView as more
    // scores come available
    public class ScoresReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Score score = intent.getParcelableExtra("Score");
            scores.add(score);
            adapter.notifyDataSetChanged();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(scoreReceiver, filter);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(scoreReceiver);
    }
}
