package com.example.scores.services;

import java.util.Random;

import android.app.IntentService;
import android.content.Intent;

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

public class ScoresService extends IntentService {
    public ScoresService() {
        super("ScoresService");
    }

    @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.toString());
            try {
                // wait 5-10 seconds
                Random rand = new Random();
                int randomNumber = rand.nextInt(6);
                Thread.sleep((randomNumber + 5) * 1000);
            }
            catch (Exception e) {
                System.err.println(e);
            }
        }
    }

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