package app.hima.tool;

import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import app.hima.R;
import app.hima.activity.MainActivity;
import app.hima.data.Message;
import app.hima.net.HasNewMessage;

public class NewMessageCheckService extends IntentService {
	private final static String NAME = "MessageCheck";
	public final static int TIME = 10 * 60 * 1000;

	public NewMessageCheckService() {
		super(NAME);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d(this.getClass().getSimpleName(), "Recherche de nouveau message.");
		checkMessage();
	}

	private void checkMessage() {
		try {
			List<Message> message = new HasNewMessage().execute().get();
			if(message.size() > 0)
			{
				NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
						this).setSmallIcon(R.drawable.ic_launcher)
						.setContentTitle("暇").setContentText("新しいメッセージが届きました。");

				Intent resultIntent = new Intent(this, MainActivity.class);
				TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
				stackBuilder.addParentStack(MainActivity.class);
				stackBuilder.addNextIntent(resultIntent);
				
				PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
				mBuilder.setContentIntent(resultPendingIntent);
				
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				mNotificationManager.notify(0, mBuilder.build());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}
