package com.sharefaith.thesharefaithapp.base;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.JobIntentService;
import androidx.core.app.NotificationCompat;

import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.SFMainActivity;

import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;

public class GcmIntentService extends JobIntentService
{
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    private final String TAG = "PushActivity";
    public static int pushIcon = R.drawable.icon;
	private SFConfig mConfig = new SFConfig();


    public GcmIntentService()
	{
        super( );

    }

    static void enqueueWork(Context context, Intent work)
	{
		enqueueWork(context, GcmIntentService.class, 1000, work);
	}

	/**
	 *
	 * @param intent
	 */
    @Override
    protected void onHandleWork( Intent intent )
	{
        Bundle extras = intent.getExtras();
        sendNotification(extras, intent);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        //String messageType = gcm.getMessageType( intent );

        if( !extras.isEmpty() )
		{  // has effect of unparcelling Bundle
            /**
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             *
            if( GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals( messageType ) )
			{
                    //System.out.println("Send error: "+extras.toString());
                    sendNotification(extras, intent);
            }
			else if( GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals( messageType ) )
			{
                    //System.out.println( "Deleted messages on server: " + extras.toString() );
                    sendNotification( extras, intent );
                // If it's a regular GCM message, do some work.
            }
			else if( GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals( messageType ) )
			{*/

                // Post notification of received message.
                sendNotification( extras, intent );
            //}
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        //GcmBroadcastReceiver.( intent );
    }


    /**
         DO SOMETHING WITH THE MESSAGE
         We are just registering the message to the notification dropdown in android
         and then separately displaying the message in a popup in app

        Variables: msg is the json string of arguments from PusServe.sharefaith.com
            As an example the following is sent from pushserve array('message' => 'Hello message', 'title' => 'Push From PushServe')
     */
    private void sendNotification( Bundle msg, Intent intent )
	{
		Notification.Builder mBuilder;
		//String messageText = ""; was never used
		//String messageTitle = "";
		String messageChannel = "";

		//System.out.println( "sendNotification Message: " + msg.toString() );

		String messageTitle = msg.getString( "message", "" );

		SFPushHandler ph = new SFPushHandler(this.getApplicationContext());
		ph.prepareIncoming( msg );

		if( ("").equals(messageTitle) || messageTitle == null )
		{
			//System.out.println( "Message variable was empty, trying default variable" );
			try
			{
				messageTitle = msg.getString( "default" ); //AWS SENDS GENERIC MESSAGES USING THE KEY "default"
			}
			catch( Exception e2 )
			{

			}
		}

		//System.out.println( "sendNotification messageTitle: " + messageTitle );
		//System.out.println( "sendNotification messageChannel: "  + messageChannel );

		SharedPreferences settings = getSharedPreferences( "Preferences", 0 );
		SharedPreferences.Editor editor = settings.edit();
		editor.putString( "channel", messageChannel );

		editor.commit();

        /*
            Registering the message to the notification dropdown in android
            Send them to an activity
        */
		mNotificationManager = (NotificationManager)
				this.getSystemService( Context.NOTIFICATION_SERVICE );

		Intent launchActivity = new Intent( this, SFMainActivity.class ); //LAUNCH AN INTENT WITH THIS PUSH

		int intentFlags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
				? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
				: PendingIntent.FLAG_UPDATE_CURRENT;

		PendingIntent contentIntent = PendingIntent.getActivity( this, 0, launchActivity, intentFlags);
		Uri alarmSound = RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION );

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
		{
			mBuilder = new Notification.Builder( this, NotificationUtils.ANDROID_CHANNEL_ID);
		} else {
			mBuilder = new Notification.Builder( this);
		}
		mBuilder
			//.setTicker(String.valueOf(R.string.app_name)).setWhen(0)
			.setSmallIcon( pushIcon )
			.setLargeIcon( BitmapFactory.decodeResource( this.getResources(), R.drawable.icon ) )
			.setContentTitle(getResources().getString(R.string.app_name))
			.setStyle( new Notification.BigTextStyle()
					.bigText( messageTitle ) )
			.setContentText( messageTitle )
			.setAutoCancel( true )
			.setSound( alarmSound )  //SOUND ALERT
			.setVibrate( new long[] { 100, 100, 100 } );  //VIBRATION ALERT

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
		{
			mBuilder.setColor( Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() ) );
			mBuilder.setSmallIcon( R.drawable.sf_notification_icon );
		}
		mBuilder.setContentIntent( contentIntent );
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

}
//this.updateLabel.setTypeface( SFTypeFaceSpan.getAssetTypeface( SFConstants.FONT_REGULAR ) );