package com.hoxfon.react.RNTwilioVoice;

import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACCEPT_CALL_INVITE;
import static com.hoxfon.react.RNTwilioVoice.Constants.INCOMING_CALL_NOTIFICATION_CHANNEL_ID;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.ACTION_CANCEL_CALL_INVITE;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.ACTION_INCOMING_CALL;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.ACTION_MISSED_CALL;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.ACTION_REJECT_CALL;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.CANCELLED_CALL_INVITE;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.INCOMING_CALL_INVITE;
import static com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule.INCOMING_CALL_NOTIFICATION_ID;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.twilio.voice.CallInvite;

import lombok.Getter;
import lombok.Setter;

public class IncomingCallNotificationService extends Service {
    private static final String TAG = IncomingCallNotificationService.class.getSimpleName();
    
    @Getter
    private static Boolean serviceInForeground = false;

    @Setter
    private static String incomingCallsNotificationChannelName;

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(onCreate): Creating the service");
        }
    }

    @Override
    public void onDestroy () {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(onDestroy): Destroying the service");
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(onStartCommand): Launching Twilio incoming call notification service by " + intent);
        }

        String action = intent.getAction();

        if (action != null) {
            CallInvite callInvite = intent.getParcelableExtra(Constants.INCOMING_CALL_INVITE);
            int notificationId = intent.getIntExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, 0);

            switch (action) {
                case Constants.ACTION_INCOMING_CALL:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_INCOMING_CALL");
                    }
                    handleIncomingCall(callInvite, notificationId);
                    break;
                case Constants.ACTION_ACCEPT:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_ACCEPT");
                    }
                    accept();
                    break;
                case Constants.ACTION_REJECT:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_REJECT");
                    }
                    reject(callInvite);
                    break;
                case Constants.ACTION_CANCEL_CALL:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_CANCEL_CALL");
                    }
                    handleCancelledCall(callInvite);
                    break;
                case Constants.ACTION_MISSED_CALL:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_MISSED_CALL");
                    }
                    handleMissedCall(callInvite);
                    break;
                case Constants.ACTION_CLEAR_MISSED_CALLS_COUNT:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_CLEAR_MISSED_CALLS_COUNT");
                    }
                    break;
                case Constants.ACTION_DISCONNECTED_CALL:
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "(onStartCommand): Executing ACTION_DISCONNECTED_CALL");
                    }
                    removeServiceFromForeground();
                    break;
                default:
                    break;
            }
        }

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void removeServiceFromForeground() {
        stopForeground(true);
        serviceInForeground = false;
    }

    private void handleIncomingCall(CallInvite callInvite, int notificationId) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(handleIncomingCall): Incoming call detected");
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setCallInProgressNotification(callInvite, notificationId);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void setCallInProgressNotification(CallInvite callInvite, int notificationId) {
        int notificationImportance = NotificationManager.IMPORTANCE_MAX;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            startForeground(
                    notificationId,
                    createNotification(callInvite, notificationId, notificationImportance)
            );
        } else {
            // Android 14
            startForeground(
                    notificationId,
                    createNotification(callInvite, notificationId, notificationImportance),
                    FOREGROUND_SERVICE_TYPE_MICROPHONE);
        }

        serviceInForeground = true;

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(setCallInProgressNotification): Show incoming call notification");
        }
    }

    public Class getMainActivityClass(ReactApplicationContext context) {
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        String className = launchIntent.getComponent().getClassName();
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Notification createNotification(CallInvite callInvite, int notificationId, int channelImportance) {
        ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
        ReactContext context = mReactInstanceManager.getCurrentReactContext();

        Intent intent = new Intent(context, getMainActivityClass((ReactApplicationContext) context));
        intent.setAction(ACTION_INCOMING_CALL);
        intent.putExtra(INCOMING_CALL_NOTIFICATION_ID, notificationId);
        intent.putExtra(INCOMING_CALL_INVITE, callInvite);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_IMMUTABLE);
        /*
         * Pass the notification id and call sid to use as an identifier to cancel the
         * notification later
         */
        Bundle extras = new Bundle();
        extras.putString(Constants.CALL_SID_KEY, callInvite.getCallSid());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return buildNotification(
                callInvite.getFrom() + " is calling.", // FIXME: Use i18n
                pendingIntent,
                extras,
                callInvite,
                notificationId,
                createChannel()
            );
        } else {
            // noinspection deprecation
            return new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_call_white_24dp)
                .setContentTitle("IslacelApp")
                .setContentText(callInvite.getFrom() + " is calling.")
                .setAutoCancel(true)
                .setExtras(extras)
                .setContentIntent(pendingIntent)
                .setGroup("test_app_notification")
                .setColor(Color.rgb(214, 10, 37)).build();
        }
    }

    /**
     * Build a notification.
     *
     * @param text          the text of the notification
     * @param pendingIntent the body, pending intent for the notification
     * @param extras        extras passed with the notification
     * @return the builder
     */
    @TargetApi(Build.VERSION_CODES.O)
    private Notification buildNotification(String text, PendingIntent pendingIntent, Bundle extras,
            final CallInvite callInvite,
            int notificationId,
            String channelId) {
        ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
        ReactContext context = mReactInstanceManager.getCurrentReactContext();

        Intent rejectIntent = new Intent(getApplicationContext(), IncomingCallNotificationService.class);
        rejectIntent.setAction(Constants.ACTION_REJECT);
        rejectIntent.putExtra(Constants.INCOMING_CALL_INVITE, callInvite);
        rejectIntent.putExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, notificationId);
        PendingIntent piRejectIntent = PendingIntent.getService(getApplicationContext(), 0, rejectIntent,
                PendingIntent.FLAG_IMMUTABLE);

        Intent acceptIntent = new Intent(context, getMainActivityClass((ReactApplicationContext) context));
        acceptIntent.setAction("android.intent.action.MAIN");
        acceptIntent.addCategory("android.intent.category.LAUNCHER");
        acceptIntent.putExtra(ACCEPT_CALL_INVITE, true);
        acceptIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent piAcceptIntent = PendingIntent.getActivity(context, 0, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);

        Notification.Builder builder = new Notification.Builder(getApplicationContext(), channelId)
                .setSmallIcon(R.drawable.ic_call_white_24dp)
                .setContentTitle("IslacelApp")
                .setContentText(text)
                .setCategory(Notification.CATEGORY_CALL)
                .setExtras(extras)
                .setAutoCancel(false)
                .setOngoing(true)
                .setVibrate(new long[] {0, 250, 250, 250})
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setPriority(Notification.PRIORITY_MAX)
                .addAction(android.R.drawable.ic_menu_delete, "DISMISS", piRejectIntent)
                .addAction(android.R.drawable.ic_menu_call, "ANSWER", piAcceptIntent)
                .setFullScreenIntent(pendingIntent, true);

        return builder.build();
    }

    @TargetApi(Build.VERSION_CODES.O)
    private String createChannel() {
        NotificationChannel callInviteChannel = new NotificationChannel(INCOMING_CALL_NOTIFICATION_CHANNEL_ID,
            incomingCallsNotificationChannelName, NotificationManager.IMPORTANCE_HIGH);
        callInviteChannel.setLightColor(Color.GREEN);
        callInviteChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        callInviteChannel.setVibrationPattern(new long[] {0, 250, 250, 250});
        callInviteChannel.enableVibration(true);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(callInviteChannel);

        return INCOMING_CALL_NOTIFICATION_CHANNEL_ID;
    }

    private void accept() {
        removeServiceFromForeground();
    }

    private void reject(CallInvite callInvite) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(reject): Incoming call rejected by user");
        }

        removeServiceFromForeground();

        publishEvent(ACTION_REJECT_CALL, null);
    }

    private void handleCancelledCall(CallInvite cancelledCallInvite) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(handleCancelledCall): Incoming call canceled");
        }

        removeServiceFromForeground();

        Bundle extras = new Bundle();
        extras.putParcelable(CANCELLED_CALL_INVITE, cancelledCallInvite);
        publishEvent(ACTION_CANCEL_CALL_INVITE, extras);
    }

    private void handleMissedCall(CallInvite callInvite) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(handleMissedCall): Incoming call missed");
        }

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(() -> {
            ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost()
                    .getReactInstanceManager();
            ReactContext context = mReactInstanceManager.getCurrentReactContext();

            CallNotificationManager callNotificationManager = new CallNotificationManager();

            if (context != null) {
                callNotificationManager.createMissedCallNotification((ReactApplicationContext) context, callInvite);
            } else {
                // Otherwise wait for construction, then handle the incoming call
                mReactInstanceManager
                        .addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
                            public void onReactContextInitialized(ReactContext context) {
                                callNotificationManager.createMissedCallNotification((ReactApplicationContext) context, callInvite);
                            }
                        });
                if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
                    // Construct it in the background
                    mReactInstanceManager.createReactContextInBackground();
                }
            }
        });

        Bundle extras = new Bundle();
        extras.putParcelable(CANCELLED_CALL_INVITE, callInvite);
        publishEvent(ACTION_MISSED_CALL, extras);

        removeServiceFromForeground();
    }

    private void publishEvent(String action, Bundle extras) {
        Intent intent = new Intent(action);

        if (extras != null && !extras.isEmpty()) {
            intent.putExtras(extras);
        }

        ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost()
                .getReactInstanceManager();
        ReactContext context = mReactInstanceManager.getCurrentReactContext();

        LocalBroadcastManager.getInstance((ReactApplicationContext) context).sendBroadcast(intent);
    }
}
