package com.hoxfon.react.RNTwilioVoice;

import static com.hoxfon.react.RNTwilioVoice.Constants.ACCEPT_CALL_INVITE;
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.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.EventManager.EVENT_CALL_INVITE_CANCELLED;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_CALL_STATE_RINGING;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_CONNECTION_DID_CONNECT;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_CONNECTION_DID_DISCONNECT;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_CONNECTION_DID_RECONNECT;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_CONNECTION_IS_RECONNECTING;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_DEVICE_DID_RECEIVE_INCOMING;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_DEVICE_DID_RECEIVE_MISSED;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_DEVICE_NOT_READY;
import static com.hoxfon.react.RNTwilioVoice.EventManager.EVENT_DEVICE_READY;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.AssertionException;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.google.firebase.messaging.FirebaseMessaging;
import com.twilio.voice.CallInvite;
import com.twilio.voice.CancelledCallInvite;
import com.twilio.voice.LogLevel;
import com.twilio.voice.RegistrationException;
import com.twilio.voice.RegistrationListener;
import com.twilio.voice.Voice;

import java.util.HashMap;
import java.util.Map;

public class TwilioVoiceModule extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
    public static String TAG = "RNTwilioVoice";
    private static final int MIC_PERMISSION_REQUEST_CODE = 1;
    private boolean isReceiverRegistered = false;
    private VoiceBroadcastReceiver voiceBroadcastReceiver;
    private TwilioVoiceCallBroadcastReceiver twilioVoiceCallBroadcastReceiver;

    public static final String INCOMING_CALL_INVITE          = "INCOMING_CALL_INVITE";
    public static final String INCOMING_CALL_NOTIFICATION_ID = "INCOMING_CALL_NOTIFICATION_ID";
    public static final String NOTIFICATION_TYPE             = "NOTIFICATION_TYPE";
    public static final String CANCELLED_CALL_INVITE         = "CANCELLED_CALL_INVITE";


    public static final String ACTION_INCOMING_CALL = "com.hoxfon.react.TwilioVoice.INCOMING_CALL";
    public static final String ACTION_FCM_TOKEN     = "com.hoxfon.react.TwilioVoice.ACTION_FCM_TOKEN";
    public static final String ACTION_MISSED_CALL   = "com.hoxfon.react.TwilioVoice.MISSED_CALL";
    public static final String ACTION_ANSWER_CALL   = "com.hoxfon.react.TwilioVoice.ANSWER_CALL";
    public static final String ACTION_REJECT_CALL   = "com.hoxfon.react.TwilioVoice.REJECT_CALL";
    public static final String ACTION_HANGUP_CALL   = "com.hoxfon.react.TwilioVoice.HANGUP_CALL";
    public static final String ACTION_CANCEL_CALL_INVITE = "com.hoxfon.react.TwilioVoice.CANCEL_CALL_INVITE";
    public static final String ACTION_CLEAR_MISSED_CALLS_COUNT = "com.hoxfon.react.TwilioVoice.CLEAR_MISSED_CALLS_COUNT";

    public static final String CALL_SID_KEY = "CALL_SID";
    public static final String INCOMING_NOTIFICATION_PREFIX = "Incoming_";
    public static final String MISSED_CALLS_GROUP = "MISSED_CALLS";
    public static final String APP_NOT_SHOW_LOCK_SCREEN = "APP_NOT_SHOW_LOCK_SCREEN";
    public static final int MISSED_CALLS_NOTIFICATION_ID = 1;
    public static final int HANGUP_NOTIFICATION_ID = 11;
    public static final int CLEAR_MISSED_CALLS_NOTIFICATION_ID = 21;

    public static final String PREFERENCE_KEY = "com.hoxfon.react.TwilioVoice.PREFERENCE_FILE_KEY";

    private ReadableMap _settings;

    private NotificationManager notificationManager;
    private CallNotificationManager callNotificationManager;

    private String accessToken;
    static Map<String, Integer> callNotificationMap;
    private RegistrationListener registrationListener = registrationListener();
    private CallInvite activeCallInvite;

    // this variable determines when to create missed calls notifications
    private Boolean callAccepted = false;
    private Boolean userInteraction = false;

    private EventManager eventManager;

    private ReactApplicationContext reactContext;

    public TwilioVoiceModule(ReactApplicationContext reactContext, boolean shouldAskForMicPermission) {
        super(reactContext);

        if (BuildConfig.DEBUG) {
            Voice.setLogLevel(LogLevel.DEBUG);
        } else {
            Voice.setLogLevel(LogLevel.ERROR);
        }

        this.reactContext = reactContext;

        reactContext.addActivityEventListener(this);
        reactContext.addLifecycleEventListener(this);

        eventManager = new EventManager(reactContext);
        callNotificationManager = new CallNotificationManager();

        notificationManager = (android.app.NotificationManager) reactContext.getSystemService(Context.NOTIFICATION_SERVICE);

        /*
         * Setup the broadcast receiver to be notified of GCM Token updates
         * or incoming call messages in this Activity.
         */
        voiceBroadcastReceiver = new VoiceBroadcastReceiver();
        twilioVoiceCallBroadcastReceiver = new TwilioVoiceCallBroadcastReceiver();
        registerReceiver();

        TwilioVoiceModule.callNotificationMap = new HashMap<>();

        /*
         * Needed for setting/abandoning audio focus during a call
         */
        // audioManager = (AudioManager) reactContext.getSystemService(Context.AUDIO_SERVICE);

        /*
         * Ensure the microphone permission is enabled
         */
        if (shouldAskForMicPermission && !checkPermissionForMicrophone()) {
            requestPermissionForMicrophone();
        }
    }

    @ReactMethod
    public void setup(ReadableMap options) {
        this._settings = options;

        if (options != null) {
            IncomingCallNotificationService.setIncomingCallsNotificationChannelName(
                options.hasKey("incomingCallsNotificationChannelName") ? 
                options.getString("incomingCallsNotificationChannelName") : "Incoming calls"
                );
            
            TwilioVoiceService.setOutgoingCallsNotificationChannelName(
                options.hasKey("outgoingCallsNotificationChannelName") ? 
                options.getString("outgoingCallsNotificationChannelName") : "Outgoing calls"
                );

            TwilioVoiceService.setOutgoingCallNotificationTitle(
                options.hasKey("outgoingCallNotificationTitle") ? 
                options.getString("outgoingCallNotificationTitle") : "Call in progress"
                );

            TwilioVoiceService.setOutgoingCallNotificationButtonTitle(
                options.hasKey("outgoingCallNotificationButtonTitle") ? 
                options.getString("outgoingCallNotificationButtonTitle") : "HANG UP"
                );
        }
    }

    @Override
    public void onHostResume() {
        /*
         * Enable changing the volume using the up/down keys during a conversation
         */
        getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
        registerReceiver();
    }

    @Override
    public void onHostPause() {
        // the library needs to listen for events even when the app is paused
        // unregisterReceiver();
    }

    @Override
    public void onHostDestroy() {
        disconnect();
    }

    @Override
    public String getName() {
        return TAG;
    }

    public void onNewIntent(Intent intent) {
        // This is called only when the App is in the foreground
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey(ACCEPT_CALL_INVITE) && bundle.getBoolean(ACCEPT_CALL_INVITE)) {
            acceptInvite();
        }
    }

    private RegistrationListener registrationListener() {
        return new RegistrationListener() {
            @Override
            public void onRegistered(String accessToken, String fcmToken) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Successfully registered FCM");
                }
                eventManager.sendEvent(EVENT_DEVICE_READY, null);
            }

            @Override
            public void onError(RegistrationException error, String accessToken, String fcmToken) {
                Log.e(TAG, String.format("Registration Error: %d, %s", error.getErrorCode(), error.getMessage()));
                WritableMap params = Arguments.createMap();
                params.putString("err", error.getMessage());
                eventManager.sendEvent(EVENT_DEVICE_NOT_READY, params);
            }
        };
    }

    /**
     * Register the Voice broadcast receiver
     */
    private void registerReceiver() {
        if (!isReceiverRegistered) {
            IntentFilter intentFilter1 = new IntentFilter();
            intentFilter1.addAction(ACTION_INCOMING_CALL);
            intentFilter1.addAction(ACTION_CANCEL_CALL_INVITE);
            intentFilter1.addAction(ACTION_MISSED_CALL);
            LocalBroadcastManager.getInstance(getReactApplicationContext()).unregisterReceiver(voiceBroadcastReceiver);
            LocalBroadcastManager.getInstance(getReactApplicationContext()).registerReceiver(voiceBroadcastReceiver, intentFilter1);
//            registerActionReceiver();
//            isReceiverRegistered = true;

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_CALL_STATE_RINGING);
            intentFilter.addAction(ACTION_CALL_CONNECTION_DID_CONNECT);
            intentFilter.addAction(ACTION_CALL_CONNECTION_IS_RECONNECTING);
            intentFilter.addAction(ACTION_CALL_CONNECTION_DID_RECONNECT);
            intentFilter.addAction(ACTION_CALL_CONNECTION_DID_DISCONNECT);
//            intentFilter.addAction(ACTION_HANGUP_CALL);
            LocalBroadcastManager.getInstance(getReactApplicationContext()).unregisterReceiver(twilioVoiceCallBroadcastReceiver);
            LocalBroadcastManager.getInstance(getReactApplicationContext()).registerReceiver(twilioVoiceCallBroadcastReceiver, intentFilter);
            registerActionReceiver();
            isReceiverRegistered = true;

            Log.d(TAG, "RIGO: registerReceiver");
        }
    }

    private void registerActionReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_ANSWER_CALL);
        intentFilter.addAction(ACTION_REJECT_CALL);
        intentFilter.addAction(ACTION_HANGUP_CALL);
        intentFilter.addAction(ACTION_CLEAR_MISSED_CALLS_COUNT);

        LocalBroadcastManager.getInstance(getReactApplicationContext()).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                switch (action) {
                    case ACTION_ANSWER_CALL:
                        acceptInvite();
                        break;
                    case ACTION_REJECT_CALL:
                        rejectInvite(false);
                        break;
                    case ACTION_HANGUP_CALL:
                        disconnect();
                        break;
                    case ACTION_CLEAR_MISSED_CALLS_COUNT:
                        SharedPreferences sharedPref = context.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
                        SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();
                        sharedPrefEditor.putInt(MISSED_CALLS_GROUP, 0);
                        sharedPrefEditor.commit();
                }
                // Dismiss the notification when the user tap on the relative notification action
                // eventually the notification will be cleared anyway
                // but in this way there is no UI lag
                notificationManager.cancel(intent.getIntExtra(INCOMING_CALL_NOTIFICATION_ID, 0));
            }
        }, intentFilter);
    }

    // removed @Override temporarily just to get it working on different versions of RN
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        onActivityResult(requestCode, resultCode, data);
    }

    // removed @Override temporarily just to get it working on different versions of RN
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Ignored, required to implement ActivityEventListener for RN 0.33
    }

    private void handleIncomingCallIntent(Intent intent) {
        if (intent == null || intent.getAction() == null) {
            return;
        }

        String action = intent.getAction();
        if (action.equals(ACTION_INCOMING_CALL)) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "handleIncomingCallIntent");
            }

            activeCallInvite = intent.getParcelableExtra(INCOMING_CALL_INVITE);
            if (activeCallInvite != null) {
                callAccepted = false;
                SoundPoolManager.getInstance(getReactApplicationContext()).playRinging();

                if (getAppNotShowLockScreen()) {
                    turnScreenOnAndKeyguardOff();
                }
                
                // send a JS event ONLY if the app's importance is FOREGROUND or SERVICE
                // at startup the app would try to fetch the activeIncoming calls
                int appImportance = callNotificationManager.getApplicationImportance(getReactApplicationContext());
                if (appImportance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
                        appImportance == RunningAppProcessInfo.IMPORTANCE_SERVICE) {
                    WritableMap params = Arguments.createMap();
                    params.putString("call_sid", activeCallInvite.getCallSid());
                    params.putString("call_from", activeCallInvite.getFrom());
                    params.putString("call_to", activeCallInvite.getTo());
                    eventManager.sendEvent(EVENT_DEVICE_DID_RECEIVE_INCOMING, params);
                }
            } 
            else {
                Log.e(TAG, "ACTION_INCOMING_CALL but not active call");
            }
        }
        else if (action.equals(ACTION_CANCEL_CALL_INVITE)) {
            SoundPoolManager.getInstance(getReactApplicationContext()).stopRinging();

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "activeCallInvite was cancelled by " + activeCallInvite.getFrom());
            }
        }
        else if (action.equals(ACTION_FCM_TOKEN)) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "handleIncomingCallIntent ACTION_FCM_TOKEN");
            }

            registerForCallInvites();
        }
    }

    private class VoiceBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Intent " + intent);
                Log.d(TAG, "VoiceBroadcastReceiver.onReceive " + action + ". Intent " + intent.getExtras());
            }

            if (action.equals(ACTION_INCOMING_CALL)) {
                userInteraction = false;
                callAccepted = false;
                handleIncomingCallIntent(intent);
            }
            else if (action.equals(ACTION_CANCEL_CALL_INVITE)) {
                Log.e(TAG, "User interaction: " + userInteraction);

                CancelledCallInvite cancelledCallInvite = intent.getParcelableExtra(CANCELLED_CALL_INVITE);
                WritableMap params = Arguments.createMap();
                if (cancelledCallInvite != null) {
                    params.putString("call_sid", cancelledCallInvite.getCallSid());
                    params.putString("call_from", cancelledCallInvite.getFrom());
                    params.putString("call_to", cancelledCallInvite.getTo());
                }

                Intent intent2 = new Intent(getReactApplicationContext(), IncomingCallNotificationService.class);
                intent2.setAction(userInteraction ? Constants.ACTION_DISCONNECTED_CALL : Constants.ACTION_MISSED_CALL);
                intent2.putExtra(INCOMING_CALL_INVITE, activeCallInvite);
                context.startService(intent2);

                eventManager.sendEvent(EVENT_CALL_INVITE_CANCELLED, params);
            }
            else if (action.equals(ACTION_MISSED_CALL)) {
                activeCallInvite = null;
                eventManager.sendEvent(EVENT_DEVICE_DID_RECEIVE_MISSED, null);
            }
            else {
                Log.e(TAG, "received broadcast unhandled action " + action);
            }
        }
    }

    private void handleInvite(int notificationId) {
        Intent intent = new Intent(getReactApplicationContext(), IncomingCallNotificationService.class);
        intent.setAction(Constants.ACTION_INCOMING_CALL);
        intent.putExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, notificationId);
        intent.putExtra(Constants.INCOMING_CALL_INVITE, activeCallInvite);

        getCurrentActivity().startService(intent);
    }

    @ReactMethod
    public void initWithAccessToken(final String accessToken, Promise promise) {
        if (accessToken.equals("")) {
            promise.reject(new JSApplicationIllegalArgumentException("Invalid access token"));
            return;
        }

        if (!checkPermissionForMicrophone()) {
            promise.reject(new AssertionException("Allow microphone permission"));
            return;
        }

        TwilioVoiceModule.this.accessToken = accessToken;

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(initWithAccessToken): Token registered successfully");
        }

        registerForCallInvites();
        
        WritableMap params = Arguments.createMap();
        params.putBoolean("initialized", true);
        promise.resolve(params);
    }

    private void clearIncomingNotification(String callSid) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "clearIncomingNotification() callSid: "+ callSid);
        }
        // remove incoming call notification
        String notificationKey = INCOMING_NOTIFICATION_PREFIX + callSid;
        int notificationId = 0;
        if (TwilioVoiceModule.callNotificationMap.containsKey(notificationKey)) {
            notificationId = TwilioVoiceModule.callNotificationMap.get(notificationKey);
        }
        callNotificationManager.removeIncomingCallNotification(getReactApplicationContext(), null, notificationId);
        TwilioVoiceModule.callNotificationMap.remove(notificationKey);
        activeCallInvite = null;
    }

    /*
     * Register your FCM token with Twilio to receive incoming call invites
     *
     * If a valid google-services.json has not been provided or the FirebaseInstanceId has not been
     * initialized the fcmToken will be null.
     *
     */
    private void registerForCallInvites() {
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(task -> {
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "getInstanceId failed", task.getException());
                        return;
                    }

                    // Get new FCM registration token
                    String fcmToken = task.getResult();

                    if (fcmToken != null) {
                        if (BuildConfig.DEBUG) {
                            Log.d(TAG, "Registering with FCM");
                        }
                        Voice.register(accessToken, Voice.RegistrationChannel.FCM, fcmToken, registrationListener);
                    }
                });
    }

    private void acceptInvite() {
        callAccepted = true;
        userInteraction = true;

        SoundPoolManager.getInstance(getReactApplicationContext()).stopRinging();

        if (activeCallInvite != null) {
            TwilioVoiceService.setReactApplicationContext(this.reactContext);
            TwilioVoiceService.setActiveCallInvite(activeCallInvite);

            Context context = getReactApplicationContext();

            Intent callServiceIntent = new Intent(getReactApplicationContext(), TwilioVoiceService.class);
            callServiceIntent.putExtra(INCOMING_CALL_INVITE, activeCallInvite);
            context.startService(callServiceIntent);

            activeCallInvite = null;
            turnScreenOnAndKeyguardOff();
        } else {
            eventManager.sendEvent(EVENT_CONNECTION_DID_DISCONNECT, null);
        }
    }

    @ReactMethod
    public void accept() {
        acceptInvite();
    }


    public void rejectInvite(Boolean notifyIncomingCallService) {
        callAccepted = false;
        userInteraction = true;
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(reject): userInteraction = true");
        }

        SoundPoolManager.getInstance(getReactApplicationContext()).stopRinging();
        WritableMap params = Arguments.createMap();
        if (activeCallInvite != null) {
            params.putString("call_sid",   activeCallInvite.getCallSid());
            params.putString("call_from",  activeCallInvite.getFrom());
            params.putString("call_to",    activeCallInvite.getTo());
            params.putString("call_state", "DISCONNECTED");
            // TODO check if DISCONNECTED should be REJECTED
            // params.putString("call_state", "REJECTED");
            activeCallInvite.reject(getReactApplicationContext());
//            clearIncomingNotification(activeCallInvite.getCallSid());
            activeCallInvite = null;

            if(notifyIncomingCallService) {
                Intent intent = new Intent(getReactApplicationContext(), IncomingCallNotificationService.class);
                intent.setAction(Constants.ACTION_REJECT);
                intent.putExtra(Constants.INCOMING_CALL_INVITE, activeCallInvite);
                getCurrentActivity().startService(intent);
            }

        }
        turnScreenOffAndKeyguardOn();
        eventManager.sendEvent(EVENT_CONNECTION_DID_DISCONNECT, params);
    }

    @ReactMethod
    public void reject() {
        rejectInvite(true);
    }

    @ReactMethod
    public void ignore() {
        callAccepted = false;
        userInteraction = false;

        SoundPoolManager.getInstance(getReactApplicationContext()).stopRinging();
        WritableMap params = Arguments.createMap();
        if (activeCallInvite != null) {
            params.putString("call_sid",   activeCallInvite.getCallSid());
            params.putString("call_from",  activeCallInvite.getFrom());
            params.putString("call_to",    activeCallInvite.getTo());
            params.putString("call_state", "BUSY");
//            clearIncomingNotification(activeCallInvite.getCallSid());
            activeCallInvite = null;
        }
//        turnScreenOffAndKeyguardOn();
        eventManager.sendEvent(EVENT_CONNECTION_DID_DISCONNECT, params);
    }

    @ReactMethod
    public void connect(ReadableMap params) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "(connect): Connecting to Twilio with params: " + params);
        }

        WritableMap errParams = Arguments.createMap();
        
        if (accessToken == null) {
            errParams.putString("err", "Invalid access token");
            eventManager.sendEvent(EVENT_DEVICE_NOT_READY, errParams);
            return;
        }
        
        if (params == null) {
            errParams.putString("err", "Invalid parameters");
            eventManager.sendEvent(EVENT_CONNECTION_DID_DISCONNECT, errParams);
            return;
        } else if (!params.hasKey("To")) {
            errParams.putString("err", "Invalid To parameter");
            eventManager.sendEvent(EVENT_CONNECTION_DID_DISCONNECT, errParams);
            return;
        }
        
        String toNumber = params.getString("To");
        String toName = params.hasKey("ToName") ? params.getString("ToName") : null;
        String toFormattedNumber = params.hasKey("DisplayNumber") ? params.getString("DisplayNumber") : null;

        TwilioVoiceService.setReactApplicationContext(this.reactContext);
        
        Intent intent = new Intent(getReactApplicationContext(), TwilioVoiceService.class);
        intent.putExtra(CALLER_NUMBER, toNumber);
        intent.putExtra(CALLER_FORMATTED_NUMBER, toFormattedNumber);
        intent.putExtra(CALLER_NAME, toName);
        intent.putExtra(ACCESS_TOKEN, accessToken);

        getCurrentActivity().startService(intent);
    }

    @ReactMethod
    public void disconnect() {
        if (TwilioVoiceService.getActiveCall() != null) {
            TwilioVoiceService.getActiveCall().disconnect();
            turnScreenOffAndKeyguardOn();
        }
    }

    @ReactMethod
    public void setMuted(Boolean value) {
        if (TwilioVoiceService.getActiveCall() != null) {
            TwilioVoiceService.getActiveCall().mute(value);
        }
    }

    @ReactMethod
    public void sendDigits(String digits) {
        if (TwilioVoiceService.getActiveCall() != null) {
            TwilioVoiceService.getActiveCall().sendDigits(digits);
        }
    }

    @ReactMethod
    public void getActiveCall(Promise promise) {
        if (TwilioVoiceService.getActiveCall() != null) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Active call found state = "+TwilioVoiceService.getActiveCall().getState());
            }
            WritableMap params = Arguments.createMap();
            String toNum = TwilioVoiceService.getActiveCall().getTo();
            if (toNum == null) {
                toNum = TwilioVoiceService.getToNumber();
            }
            params.putString("call_sid",   TwilioVoiceService.getActiveCall().getSid());
            params.putString("call_from",  TwilioVoiceService.getActiveCall().getFrom());
            params.putString("call_to",    toNum);
            params.putString("call_state", TwilioVoiceService.getActiveCall().getState().name());
            promise.resolve(params);
            return;
        }
        promise.resolve(null);
    }

    @ReactMethod
    public void getCallInvite(Promise promise) {
        if (activeCallInvite != null) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Call invite found "+ activeCallInvite);
            }
            WritableMap params = Arguments.createMap();
            params.putString("call_sid",   activeCallInvite.getCallSid());
            params.putString("call_from",  activeCallInvite.getFrom());
            params.putString("call_to",    activeCallInvite.getTo());
            promise.resolve(params);
            return;
        }
        promise.resolve(null);
    }

    @ReactMethod
    public void setSpeakerPhone(Boolean value) {
        // TODO check whether it is necessary to call setAudioFocus again
//        setAudioFocus();
//        audioManager.setSpeakerphoneOn(value);
        TwilioVoiceService.setSpeakerPhone(value);
    }

    @ReactMethod
    public void setOnHold(Boolean value) {
        if (TwilioVoiceService.getActiveCall() != null) {
            TwilioVoiceService.getActiveCall().hold(value);
        }
    }

    @ReactMethod
    public void setOffLockScreen() {
        turnScreenOffAndKeyguardOn();
    }

    @ReactMethod
    public void clearMissedCallNotifications() {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Clearing notifications");
        }

        Context context = getReactApplicationContext();

        SharedPreferences sharedPref = context.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();
        sharedPrefEditor.putInt(MISSED_CALLS_GROUP, 0);
        sharedPrefEditor.apply();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(MISSED_CALLS_NOTIFICATION_ID);
    }

    private boolean checkPermissionForMicrophone() {
        int resultMic = ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.RECORD_AUDIO);
        return resultMic == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissionForMicrophone() {
        if (getCurrentActivity() == null) {
            return;
        }
        if (ActivityCompat.shouldShowRequestPermissionRationale(getCurrentActivity(), Manifest.permission.RECORD_AUDIO)) {
//            Snackbar.make(coordinatorLayout,
//                    "Microphone permissions needed. Please allow in your application settings.",
//                    SNACKBAR_DURATION).show();
        } else {
            ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, MIC_PERMISSION_REQUEST_CODE);
        }
    }

    private class TwilioVoiceCallBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "TwilioVoiceCallBroadcastReceiver.onReceive "+action+". Intent "+ intent.getExtras());
            }
            Bundle extras = intent.getExtras();
            WritableMap params = Arguments.createMap();
            switch (action) {
                case ACTION_CALL_STATE_RINGING:
                    if (extras.containsKey("call_sid") && extras.containsKey("call_from")) {
                        params.putString("call_sid",   extras.getString("call_sid"));
                        params.putString("call_from",  extras.getString("call_from"));
                    }
                    eventManager.sendEvent(EVENT_CALL_STATE_RINGING, params);
                    break;
                case ACTION_CALL_CONNECTION_DID_CONNECT:
                case ACTION_CALL_CONNECTION_DID_DISCONNECT:
                    if (extras.containsKey("call_sid") && extras.containsKey("call_state") && extras.containsKey("call_from") && extras.containsKey("call_to")) {
                        params.putString("call_sid",   extras.getString("call_sid"));
                        params.putString("call_state", extras.getString("call_state"));
                        params.putString("call_from", extras.getString("call_from"));
                        params.putString("call_to", extras.getString("call_to"));
                    }
                    eventManager.sendEvent(action.equals(ACTION_CALL_CONNECTION_DID_CONNECT)? EVENT_CONNECTION_DID_CONNECT: EVENT_CONNECTION_DID_DISCONNECT, params);
                    break;
                case ACTION_CALL_CONNECTION_IS_RECONNECTING:
                case ACTION_CALL_CONNECTION_DID_RECONNECT:
                    if (extras.containsKey("call_sid") && extras.containsKey("call_from") && extras.containsKey("call_to")) {
                        params.putString("call_sid",   extras.getString("call_sid"));
                        params.putString("call_from", extras.getString("call_from"));
                        params.putString("call_to", extras.getString("call_to"));
                    }
                    eventManager.sendEvent(action.equals(ACTION_CALL_CONNECTION_IS_RECONNECTING)? EVENT_CONNECTION_IS_RECONNECTING: EVENT_CONNECTION_DID_RECONNECT, params);
                    break;
                default:
                    if (BuildConfig.DEBUG) {
                        Log.e(TAG, "received broadcast unhandled action " + action);
                    }
                    break;
            }
        }
    }

    private void turnScreenOnAndKeyguardOff() {
        final Activity activity = getCurrentActivity();

        if (activity != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
                activity.setShowWhenLocked(true);
                activity.setTurnScreenOn(true);
            } else {
                Window window = activity.getWindow();

                window.addFlags(
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                );
            }

            /*
            KeyguardManager keyguardManager = (KeyguardManager) reactContext.getSystemService(android.content.Context.KEYGUARD_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                keyguardManager.requestDismissKeyguard(activity, null);
            }
            */

            SharedPreferences sharedPref = activity.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
            SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();
            sharedPrefEditor.remove(APP_NOT_SHOW_LOCK_SCREEN);
            sharedPrefEditor.commit();
        }
    }

    private void turnScreenOffAndKeyguardOn() {
        final Activity activity = getCurrentActivity();

        if(activity != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
                activity.setShowWhenLocked(false);
                activity.setTurnScreenOn(false);
            } else {
                Window window = activity.getWindow();
                window.clearFlags(
                        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                );
            }

        SharedPreferences sharedPref = activity.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();
        sharedPrefEditor.putBoolean(APP_NOT_SHOW_LOCK_SCREEN, true);
        sharedPrefEditor.commit();
        }

    }

    private Boolean getAppNotShowLockScreen() {
        final Activity activity = getCurrentActivity();

        if (activity != null) {
            SharedPreferences sharedPref = activity.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
            return sharedPref.getBoolean(APP_NOT_SHOW_LOCK_SCREEN, false);
        } else {
            return false;
        }
    }
}
