/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.example.hello.android.service_bind_with_aidl;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

/**
 *
 * @author sawai
 */
public class CountDownService extends Service
	implements Runnable
{

	private static final long COUNT_INTERVAL_MSEC = 1000; // 1sec
	private static final int COUNT = 10;
	public static final String LOG_TAG = "XXX";
	private Handler handler;
	private boolean running;
	private int count;
	private ICountDownService.Stub binder = new ICountDownService.Stub()
	{
		public void startCountDown() throws RemoteException
		{
			CountDownService.this.startCountDown();
		}

		public void stopCountDown() throws RemoteException
		{
			CountDownService.this.stopCountDown();
		}

		public int getCount() throws RemoteException
		{
			return CountDownService.this.getCount();
		}
	};

	@Override
	public void onCreate()
	{
		Log.d(LOG_TAG, "CountDownService#onCreate() Hello");
		super.onCreate();
		handler = new Handler();
		running = false;
		Log.d(LOG_TAG, "CountDownService#onCreate() Bye");
	}

	@Override
	public void onDestroy()
	{
		Log.d(LOG_TAG, "CountDownService#onDestroy() Hello");
		stopCountDown();
		super.onDestroy();
		Log.d(LOG_TAG, "CountDownService#onDestroy() Bye");
	}

	/**
	 * This methos is not called, if using bindService().
	 *
	 * @param intent
	 * @param startId
	 */
	@Override
	public void onStart(Intent intent, int startId)
	{
		Log.d(LOG_TAG, "CountDownService#onStart() Hello");
		super.onStart(intent, startId);
		Log.d(LOG_TAG, "CountDownService#onStart() Bye");
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		Log.d(LOG_TAG, "CountDownService#onBind() Hello");
		return binder;
	}

	@Override
	public void run()
	{
		Log.d(LOG_TAG, "CountDownService#run() Hello");
		Log.d(LOG_TAG, "CountDownService#run() count : " + count);
		if (running)
		{
			count--;
			if (count <= 0)
			{
				running = false;
			}
			else
			{
				handler.postDelayed(this, COUNT_INTERVAL_MSEC);
			}
		}
		Log.d(LOG_TAG, "CountDownService#run() Bye");
	}

	public void startCountDown()
	{
		Log.d(LOG_TAG, "CountDownService#startCountDown() Hello");
		if (!running)
		{
			running = true;
			count = COUNT;
			handler.postDelayed(this, COUNT_INTERVAL_MSEC);
		}
		Log.d(LOG_TAG, "CountDownService#startCountDown() Bye");
	}

	public void stopCountDown()
	{
		Log.d(LOG_TAG, "CountDownService#stopCountDown() Hello");
		if (running)
		{
			running = false;
		}
		Log.d(LOG_TAG, "CountDownService#stopCountDown() Bye");
	}

	public int getCount()
	{
		Log.d(LOG_TAG, "CountDownService#getCount() Hello");
		return count;
	}
}
