package com.example.scores.services;

import java.util.Random;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

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

public class ScoresService2 extends Service {
    public ScoresService2() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags,
            final int startId) {
        new Thread(new Runnable() {
            public void run() {
                simulateScoreRetrieval(intent);
                stopSelf(startId);
            }
        }).start();
        return START_NOT_STICKY;
    }

    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);
    }
}