package BWP.MobileSale;

import java.util.LinkedList;

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


public class CommandService extends Service {

	public static void AddCommand(Command command){
		synchronized (mCommands) {
			mCommands.add(command);
		}
	}
	
	public interface Command{
		void Execute() throws Exception;
		String getName();
	}
	
	
	static LinkedList<Command> mCommands = new LinkedList<Command>();
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	class BackgroundTask extends  AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			while(true){
				Command command;
				synchronized(mCommands){
					command = mCommands.poll();
				}
				if(command ==null ){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					continue;
				}
				try {
					command.Execute();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
	}
	
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		new BackgroundTask().execute();
	}
}
