package com.hoxfon.react.RNTwilioVoice;

import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACCESS_TOKEN;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_CALL_CONNECTION_DID_CONNECT;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_CALL_CONNECTION_DID_DISCONNECT;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_CALL_CONNECTION_DID_RECONNECT;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_CALL_CONNECTION_IS_RECONNECTING;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_CALL_STATE_RINGING;
import static com.hoxfon.react.RNTwilioVoice.Constants.ACTION_INCOMING_CALL;
import static com.hoxfon.react.RNTwilioVoice.Constants.CALLER_FORMATTED_NUMBER;
import static com.hoxfon.react.RNTwilioVoice.Constants.CALLER_NAME;
import static com.hoxfon.react.RNTwilioVoice.Constants.CALLER_NUMBER;
import static com.hoxfon.react.RNTwilioVoice.Constants.CALL_SID_KEY;
import static com.hoxfon.react.RNTwilioVoice.Constants.HANGUP_NOTIFICATION_ID;
import static com.hoxfon.react.RNTwilioVoice.Constants.INCOMING_CALL_NOTIFICATION_ID;
import static com.hoxfon.react.RNTwilioVoice.Constants.OUTGOING_CALL_NOTIFICATION_CHANNEL_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.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.facebook.react.bridge.ReactApplicationContext;
import com.twilio.voice.AcceptOptions;
import com.twilio.voice.BuildConfig;
import com.twilio.voice.Call;
import com.twilio.voice.CallException;
import com.twilio.voice.CallInvite;
import com.twilio.voice.ConnectOptions;
import com.twilio.voice.Voice;

import java.util.HashMap;

import lombok.Setter;

public class TwilioVoiceService extends Service {
    private static final String TAG = "TwilioVoiceService";

    private static HashMap<String, String> params = new HashMap<>();
    private static Call activeCall;
    private static CallInvite activeCallInvite;
    private Call.Listener callListener = callListener();

    private static AudioFocusRequest focusRequest;
    private static HeadsetManager headsetManager;
    private static AudioManager audioManager;
    private static int originalAudioMode = AudioManager.MODE_NORMAL;
    private static ReactApplicationContext reactContext;
    private static CallNotificationManager callNotificationManager;

    private static ProximityViaPowerManager proximityViaPowerManager;

    private static String toNumber = "";
    private static String toFormattedNumber = "";
    private static String toName = "";

    @Setter private static String outgoingCallsNotificationChannelName;
    @Setter private static String outgoingCallNotificationTitle;
    @Setter private static String outgoingCallNotificationButtonTitle;

    private static Boolean inForegroundService = false;

    public static void setReactApplicationContext(ReactApplicationContext reactContext) {
        TwilioVoiceService.reactContext = reactContext;
    }

    public static ReactApplicationContext getReactApplicationContext() {
        return TwilioVoiceService.reactContext;
    }

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

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Twilio voice service was created successfully");
        }
    }

    @Override
    public void onDestroy() {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Twilio voice service was destroyed successfully");
        }

        unSetAudioFocus();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Launching Twilio voice service");
        }

        String action = intent.getAction();

        if (action != null) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Twilio voice service: Executing specified action");
            }

            switch (action) {
                case Constants.ACTION_HANGUP_CALL:
                    hangoutCall();
                    break;
                default:
                    break;
            }
        } else {
            if (intent != null) {
                setupService(intent);
            } else {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Twilio voice service was restarted");
                }
            }
        }

        return START_NOT_STICKY;
    }

    /**
     * Terminate the current call from notification
     */
    private void hangoutCall() {
        stopService();

        if (activeCall != null) {
            activeCall.disconnect();
        }
    }

    private void startForegroundService(String callSid) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            // Bypass this before SDK 28
            return;
        }

        String caller = TwilioVoiceService.toNumber;
        if (TwilioVoiceService.toFormattedNumber != null && !TwilioVoiceService.toFormattedNumber.equals("")) {
            caller = TwilioVoiceService.toFormattedNumber;
        }
        if (TwilioVoiceService.toName != null && !TwilioVoiceService.toName.equals("")) {
            caller = TwilioVoiceService.toName;
        }

        // startForeground(FOREGROUND_SERVICE_TYPE_MICROPHONE, TwilioVoiceService.callNotificationManager.getHangupLocalNotification(getReactApplicationContext(), callSid, caller, TwilioVoiceService.progressText, TwilioVoiceService.progressAction));

        int SERVICE_ID = FOREGROUND_SERVICE_TYPE_MICROPHONE;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            startForeground(
                    SERVICE_ID,
                    getHangupLocalNotification(callSid, caller)
            );
        } else {
            // Android 14
            startForeground(
                    SERVICE_ID,
                    getHangupLocalNotification(callSid, caller),
                    FOREGROUND_SERVICE_TYPE_MICROPHONE);
        }

        TwilioVoiceService.inForegroundService = true;
    }

    /**
     * Kills current service
     */
    private void stopService() {
        if (TwilioVoiceService.inForegroundService) {
            stopForeground(true);
            TwilioVoiceService.inForegroundService = false;
        }

        stopSelf();
    }

    /**
     * Setting up the current service based on params passed by a launcher intent
     * @param intent
     */
    private void setupService(Intent intent) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Twilio voice service: Setting up service");
        }

        TwilioVoiceService.proximityViaPowerManager = new ProximityViaPowerManager(getReactApplicationContext());

        TwilioVoiceService.headsetManager = new HeadsetManager(null);
        TwilioVoiceService.audioManager = (AudioManager) getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        TwilioVoiceService.callNotificationManager = new CallNotificationManager();

        TwilioVoiceService.toNumber = intent.getStringExtra(CALLER_NUMBER);
        TwilioVoiceService.toFormattedNumber = intent.getStringExtra(CALLER_FORMATTED_NUMBER);
        TwilioVoiceService.toName = intent.getStringExtra(CALLER_NAME);
        String accessToken = intent.getStringExtra(ACCESS_TOKEN);
        
        startCallProcess(accessToken);
    }

    /**
     * Starting up the call connection
     * @param accessToken
     */
    private void startCallProcess(String accessToken) {
        if (TwilioVoiceService.activeCallInvite != null) {
            TwilioVoiceService.toNumber = TwilioVoiceService.activeCallInvite.getFrom();
            // TwilioVoiceService.toName = TwilioVoiceService.activeCallInvite.getFrom();

            AcceptOptions acceptOptions = new AcceptOptions.Builder()
                    .enableDscp(true)
                    .build();
            TwilioVoiceService.activeCall = TwilioVoiceService.activeCallInvite.accept(getReactApplicationContext(), acceptOptions, callListener);
            TwilioVoiceService.activeCallInvite = null;

            Bundle extras = new Bundle();
            extras.putString("call_sid",   activeCall.getSid());
            extras.putString("call_state", activeCall.getState().name());
            extras.putString("call_from", activeCall.getFrom());
            extras.putString("call_to", activeCall.getTo());
            startForegroundService(activeCall.getSid());

            publishEvent(ACTION_CALL_CONNECTION_DID_CONNECT, extras);
            Log.d(TAG, "Twilio voice call was started successfully");

            return;
        }

        TwilioVoiceService.params.clear();
        TwilioVoiceService.params.put("To", TwilioVoiceService.toNumber);
        // TODO: Send custom parameters to TwiML
        ConnectOptions connectOptions = new ConnectOptions.Builder(accessToken)
                .params(TwilioVoiceService.params)
                .build();

        TwilioVoiceService.activeCall = Voice.connect(this, connectOptions, callListener);
    }

    private Call.Listener callListener() {
        return new Call.Listener() {
            @Override
            public void onConnectFailure(@NonNull Call call, @NonNull CallException callException) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "CALL FAILURE callListener().onConnectFailure call state = "+call.getState());
                }
                TwilioVoiceService.unSetAudioFocus();
                TwilioVoiceService.proximityViaPowerManager.desactivate();
                Bundle extras = new Bundle();
                String callSid = "";
                if (call != null) {
                    callSid = call.getSid();
                    extras.putString("call_sid", callSid);
                    extras.putString("call_state", call.getState().name());
                    extras.putString("call_from", call.getFrom());
                    extras.putString("call_to", call.getTo());
                }
                if (callException != null) {
                    Log.e(TAG, String.format("CallListener onConnectFailure error: %d, %s",
                            callException.getErrorCode(), callException.getMessage()));
                    extras.putString("err", callException.getMessage());
                }
                if (callSid != null && TwilioVoiceService.activeCall != null && TwilioVoiceService.activeCall.getSid() != null && TwilioVoiceService.activeCall.getSid().equals(callSid)) {
                    TwilioVoiceService.activeCall = null;
                }

                stopService();
                TwilioVoiceService.toNumber = "";
                TwilioVoiceService.toFormattedNumber = "";
                TwilioVoiceService.toName = "";
                publishEvent(ACTION_CALL_CONNECTION_DID_DISCONNECT, extras);
            }

            @Override
            public void onRinging(@NonNull Call call) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "(callListener.onRinging) Current call state: " + call.getState());
                }

                Bundle extras = new Bundle();
                if (call != null) {
                    extras.putString("call_sid",   call.getSid());
                    extras.putString("call_from",  call.getFrom());
                }

                publishEvent(ACTION_CALL_STATE_RINGING, extras);
            }

            @Override
            public void onConnected(@NonNull Call call) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "(callListener.onConnected) Current call state: " + call.getState());
                }

                TwilioVoiceService.setAudioFocus();
                TwilioVoiceService.proximityViaPowerManager.activate();
                TwilioVoiceService.headsetManager.startWiredHeadsetEvent(getReactApplicationContext());

                Bundle extras = new Bundle();
                if (call != null) {
                    extras.putString("call_sid",   call.getSid());
                    extras.putString("call_state", call.getState().name());
                    extras.putString("call_from", call.getFrom());
                    extras.putString("call_to", call.getTo());
                    TwilioVoiceService.activeCall = call;
                    startForegroundService(call.getSid());
                }

                publishEvent(ACTION_CALL_CONNECTION_DID_CONNECT, extras);
            }

            @Override
            public void onReconnecting(@NonNull Call call, @NonNull CallException callException) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "CALL RECONNECTING callListener().onReconnecting call state = "+call.getState());
                }
                Bundle extras = new Bundle();
                if (call != null) {
                    extras.putString("call_sid",   call.getSid());
                    extras.putString("call_from", call.getFrom());
                    extras.putString("call_to", call.getTo());
                }

                publishEvent(ACTION_CALL_CONNECTION_IS_RECONNECTING, extras);
            }

            @Override
            public void onReconnected(@NonNull Call call) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "CALL RECONNECTED callListener().onReconnected call state = "+call.getState());
                }
                Bundle extras = new Bundle();
                if (call != null) {
                    extras.putString("call_sid",   call.getSid());
                    extras.putString("call_from", call.getFrom());
                    extras.putString("call_to", call.getTo());
                }

                publishEvent(ACTION_CALL_CONNECTION_DID_RECONNECT, extras);
            }

            @Override
            public void onDisconnected(@NonNull Call call, @Nullable CallException callException) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "(callListener.onDisconnected) Current call state: " + call.getState());
                }

                TwilioVoiceService.unSetAudioFocus();
                TwilioVoiceService.proximityViaPowerManager.desactivate();
                TwilioVoiceService.headsetManager.stopWiredHeadsetEvent(getReactApplicationContext());

                Bundle extras = new Bundle();
                String callSid = "";
                if (call != null) {
                    callSid = call.getSid();
                    extras.putString("call_sid", callSid);
                    extras.putString("call_state", call.getState().name());
                    extras.putString("call_from", call.getFrom());
                    extras.putString("call_to", call.getTo());
                }
                if (callException != null) {
                    Log.e(TAG, String.format("CallListener onDisconnected error: %d, %s",
                            callException.getErrorCode(), callException.getMessage()));
                    extras.putString("err", callException.getMessage());
                }
                if (callSid != null && TwilioVoiceService.activeCall != null && TwilioVoiceService.activeCall.getSid() != null && TwilioVoiceService.activeCall.getSid().equals(callSid)) {
                    TwilioVoiceService.activeCall = null;
                }

                stopService();
                TwilioVoiceService.toNumber = "";
                TwilioVoiceService.toFormattedNumber = "";
                TwilioVoiceService.toName = "";
                publishEvent(ACTION_CALL_CONNECTION_DID_DISCONNECT, extras);
            }
        };
    }

    private static void setAudioFocus() {
        if (TwilioVoiceService.audioManager == null) {
            TwilioVoiceService.audioManager.setMode(TwilioVoiceService.originalAudioMode);
            TwilioVoiceService.audioManager.abandonAudioFocus(null);
            return;
        }
        TwilioVoiceService.originalAudioMode = TwilioVoiceService.audioManager.getMode();
        // Request audio focus before making any device switch
        if (Build.VERSION.SDK_INT >= 26) {
            AudioAttributes playbackAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();
            TwilioVoiceService.focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)
                    .setAudioAttributes(playbackAttributes)
                    .setAcceptsDelayedFocusGain(true)
                    .setOnAudioFocusChangeListener(i -> { })
                    .build();
            TwilioVoiceService.audioManager.requestAudioFocus(TwilioVoiceService.focusRequest);
        } else {
            int focusRequestResult = TwilioVoiceService.audioManager.requestAudioFocus(focusChange -> {},
                    AudioManager.STREAM_VOICE_CALL,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        }
        /*
         * Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
         * required to be in this mode when playout and/or recording starts for
         * best possible VoIP performance. Some devices have difficulties with speaker mode
         * if this is not set.
         */
        TwilioVoiceService.audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    }

    private static void unSetAudioFocus() {
        if (TwilioVoiceService.audioManager == null) {
            TwilioVoiceService.audioManager.setMode(TwilioVoiceService.originalAudioMode);
            TwilioVoiceService.audioManager.abandonAudioFocus(null);
            return;
        }
        TwilioVoiceService.audioManager.setMode(TwilioVoiceService.originalAudioMode);
        if (Build.VERSION.SDK_INT >= 26) {
            if (TwilioVoiceService.focusRequest != null) {
                TwilioVoiceService.audioManager.abandonAudioFocusRequest(TwilioVoiceService.focusRequest);
            }
        } else {
            TwilioVoiceService.audioManager.abandonAudioFocus(null);
        }
    }

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

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

        LocalBroadcastManager.getInstance(getReactApplicationContext()).sendBroadcast(intent);
    }

    public static Call getActiveCall() {
        return TwilioVoiceService.activeCall;
    }

    public static String getToNumber() {
        return TwilioVoiceService.toNumber;
    }

    public static void setSpeakerPhone(Boolean value) {
        TwilioVoiceService.setAudioFocus();
        TwilioVoiceService.audioManager.setSpeakerphoneOn(value);
    }

    public static CallInvite getActiveCallInvite() {
        return activeCallInvite;
    }

    public static void setActiveCallInvite(CallInvite activeCallInvite) {
        TwilioVoiceService.activeCallInvite = activeCallInvite;
    }

    public Notification getHangupLocalNotification(String callSid, String caller) {
        Intent rejectIntent = new Intent(getApplicationContext(), TwilioVoiceService.class);
        rejectIntent.setAction(Constants.ACTION_HANGUP_CALL);
        rejectIntent.putExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, HANGUP_NOTIFICATION_ID);
        PendingIntent piRejectIntent = PendingIntent.getService(getReactApplicationContext(), 0, rejectIntent, PendingIntent.FLAG_IMMUTABLE);

        Intent launchIntent = new Intent(getApplicationContext(), getMainActivityClass());
        launchIntent.setAction(ACTION_INCOMING_CALL);
        launchIntent.putExtra(INCOMING_CALL_NOTIFICATION_ID, HANGUP_NOTIFICATION_ID);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(getReactApplicationContext(), HANGUP_NOTIFICATION_ID, launchIntent, PendingIntent.FLAG_IMMUTABLE);

        Bundle extras = new Bundle();
        extras.putString(CALL_SID_KEY, callSid);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return new Notification.Builder(getReactApplicationContext(), createChannel())
                    .setContentTitle(outgoingCallNotificationTitle)
                    .setContentText(caller)
                    .setSmallIcon(R.drawable.ic_call_white_24dp)
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setCategory(NotificationCompat.CATEGORY_CALL)
                    .setOngoing(true)
                    .setUsesChronometer(true)
                    .setExtras(extras)
                    .addAction(android.R.drawable.ic_menu_delete, outgoingCallNotificationButtonTitle, piRejectIntent)
                    .setContentIntent(pendingIntent).build();
        } else {
            //noinspection deprecation
            return new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_call_white_24dp)
                    .setContentTitle(outgoingCallNotificationTitle)
                    .setContentText(caller)
                    .setAutoCancel(true)
                    .setExtras(extras)
                    .setContentIntent(pendingIntent)
                    .setGroup("test_app_notification")
                    .setColor(Color.rgb(214, 10, 37)).build();
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private String createChannel() {
        NotificationChannel callInviteChannel = new NotificationChannel(OUTGOING_CALL_NOTIFICATION_CHANNEL_ID,
            outgoingCallsNotificationChannelName, NotificationManager.IMPORTANCE_LOW);
        callInviteChannel.setLightColor(Color.GREEN);
        callInviteChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(callInviteChannel);

        return OUTGOING_CALL_NOTIFICATION_CHANNEL_ID;
    }

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