package com.example.scores.services;

import java.util.ArrayList;
import java.util.Random;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;

import com.example.scores.activities.DisplayScoresActivity;
import com.example.scores.utilities.Score;
import com.example.scores.utilities.ScoreGenerator;

public class ScoresService extends IntentService {
    private ArrayList<Parcelable> scores;
    
    public ScoresService() {
        super("ScoresService");
        scores = new ArrayList<Parcelable>();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        simulateScoreRetrieval(intent);
    }

    private void simulateScoreRetrieval(Intent intent) {
        int xmlResource = intent.getIntExtra("XmlResource", 0);
        ScoreGenerator scoreGenerator = new ScoreGenerator(
                getResources().getXml(xmlResource));

        Score score = null;
        while ((score = scoreGenerator.getScore()) != null) {
            broadcastScore(score);
            notify(score);
            try {
                // wait 10-20 seconds before retrieving the next score
                Random rand = new Random();
                int randomNumber = rand.nextInt(10);
                Thread.sleep((randomNumber + 10) * 1000);
            }
            catch (Exception e) {
                System.err.println(e);
            }
        }
    }

    private void broadcastScore(Score score) {
        Intent intent = new Intent("com.example.scores.BROADCAST");
        intent.putExtra("Score", score);
        getApplicationContext().sendBroadcast(intent);
    }



    private void notify(Score score) {
        scores.add(score); // accumulate the scores in a List
        Context ctx = getApplicationContext();

        Intent intent = new Intent(ctx, DisplayScoresActivity.class);
        intent.putParcelableArrayListExtra("Scores", scores);
        
        // Add notification code here
              
    } 
}