package com.plugin.gcm;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {

	public static final int NOTIFICATION_ID = 237;
	private static final String TAG = "GCMIntentService";
	
	public GCMIntentService() {
		super("GCMIntentService");
	}

	@Override
	public void onRegistered(Context context, String regId) {

		Log.v(TAG, "onRegistered: "+ regId);

		JSONObject json;

		try
		{
			json = new JSONObject().put("event", "registered");
			json.put("regid", regId);

			Log.v(TAG, "onRegistered: " + json.toString());

			// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
			// In this case this is the registration ID
			PushPlugin.sendJavascript( json );

		}
		catch( JSONException e)
		{
			// No message to the user is sent, JSON failed
			Log.e(TAG, "onRegistered: JSON exception");
		}
	}

	@Override
	public void onUnregistered(Context context, String regId) {
		Log.d(TAG, "onUnregistered - regId: " + regId);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.d(TAG, "onMessage - context: " + context);

		// Extract the payload from the message
		Bundle extras = intent.getExtras();
		if (extras != null)
		{
            if (PushPlugin.isInForeground())
            	PushPlugin.sendExtras(extras);
            else
            {
            	try
            	{
            		JSONObject ob = PushPlugin.convertBundleToJson(extras);
            		String title = "";
            		try
            		{
            			title = ob.getString("title");
            		}
            		catch (JSONException eex)
            		{
            			title = "Nová zpráva!";
            		}
            		createNotification(context, title, ob.getString("message"), 0);
            	}
            	catch (JSONException ex)
            	{
            		Log.d("JSONParse", "Notification does not contain key! Notice: "+ex.getMessage());
            	}
            }
        }
	}

	public static void createNotification(Context context, String title, String message, int count)
	{
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		String appName = getAppName(context);

		Intent notificationIntent = new Intent(context, PushHandlerActivity.class);
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		NotificationCompat.Builder mBuilder =
			new NotificationCompat.Builder(context)
				.setDefaults(Notification.DEFAULT_ALL)
				.setSmallIcon(context.getApplicationInfo().icon)
				.setWhen(System.currentTimeMillis())
				.setContentTitle(title)
				.setTicker(title)
				.setContentIntent(contentIntent);

		if (message != null)
			mBuilder.setContentText(message);
		else
			mBuilder.setContentText("<missing message content>");

		if (count != 0)
			mBuilder.setNumber(count);
		
		mNotificationManager.notify((String) appName, NOTIFICATION_ID, mBuilder.build());
	}
	
	public static void cancelNotification(Context context)
	{
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel((String)getAppName(context), NOTIFICATION_ID);	
	}
	
	private static String getAppName(Context context)
	{
		CharSequence appName = 
				context
					.getPackageManager()
					.getApplicationLabel(context.getApplicationInfo());

		return (String)appName;
	}
	
	@Override
	public void onError(Context context, String errorId) {
		Log.e(TAG, "onError - errorId: " + errorId);
	}

}

@@ -1666,738 +1666,50 @@
     
-if (PushPlugin.isInForeground())%0A            %09PushPlugin.sendExtras(extras);%0A            else%0A            %7B%0A            %09try%0A            %09%7B%0A            %09%09JSONObject ob = PushPlugin.convertBundleToJson(extras);%0A            %09%09String title = %22%22;%0A            %09%09try%0A            %09%09%7B%0A            %09%09%09title = ob.getString(%22title%22);%0A            %09%09%7D%0A            %09%09catch (JSONException eex)%0A            %09%09%7B%0A            %09%09%09title = %22Nov%C3%A1 zpr%C3%A1va!%22;%0A            %09%09%7D%0A            %09%09createNotification(context, title, ob.getString(%22message%22), 0);%0A            %09%7D%0A            %09catch (JSONException ex)%0A            %09%7B%0A            %09%09Log.d(%22JSONParse%22, %22Notification does not contain key! Notice: %22+ex.getMessage());%0A            %09%7D%0A            %7D%0A        
+%09%09PushPlugin.sendExtras(extras);%0A        %09
 %7D%0A%09%7D

Handle push message by Cordova application even when in foreground