
package com.akcybex.sms;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;

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.Callback;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

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

import java.util.ArrayList;
import java.util.List;

public class AKSmsModule extends ReactContextBaseJavaModule {

    public static ReactApplicationContext reactContext;

    public AKSmsModule(ReactApplicationContext reactContext1) {
        super(reactContext1);
        reactContext = reactContext1;
    }

    @Override
    public String getName() {
        return "AKSms";
    }

    @ReactMethod
    public void send(final String recipient, final String message, final Callback successCallback, final Callback errorCallback) {

        Dexter.withActivity(getCurrentActivity())
                .withPermissions(
                        Manifest.permission.SEND_SMS,
                        Manifest.permission.RECEIVE_SMS,
                        Manifest.permission.READ_SMS
                ).withListener(new MultiplePermissionsListener() {
            @Override public void onPermissionsChecked(MultiplePermissionsReport report) {

                if(report.areAllPermissionsGranted()){
                    String SENT = "SMS_SENT";
                    String DELIVERED = "SMS_DELIVERED";

                    SmsManager smsManager = SmsManager.getDefault();
                    ArrayList<String> parts = smsManager.divideMessage(message);

                    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<>();
                    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<>();

                    final JSONObject jsonObject = new JSONObject();

                    //---when the SMS has been sent---
                    getCurrentActivity().registerReceiver(new BroadcastReceiver(){
                        @Override
                        public void onReceive(Context arg0, Intent arg1) {

                            switch (getResultCode())
                            {
                                case Activity.RESULT_OK:


                                    try {
                                        jsonObject.put("message", "Sms sent successfully.");
                                        jsonObject.put("type", "sent");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }


                                    successCallback.invoke(jsonObject.toString());
                                    break;
                                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                    errorCallback.invoke(String.valueOf(SmsManager.RESULT_ERROR_GENERIC_FAILURE), "Generic failure");
                                    break;
                                case SmsManager.RESULT_ERROR_NO_SERVICE:
                                    errorCallback.invoke(String.valueOf(SmsManager.RESULT_ERROR_NO_SERVICE), "No service");
                                    break;
                                case SmsManager.RESULT_ERROR_NULL_PDU:
                                    errorCallback.invoke(String.valueOf(SmsManager.RESULT_ERROR_NULL_PDU), "Null PDU");
                                    break;
                                case SmsManager.RESULT_ERROR_RADIO_OFF:
                                    errorCallback.invoke(String.valueOf(SmsManager.RESULT_ERROR_RADIO_OFF), "Radio off");
                                    break;
                            }
                        }
                    }, new IntentFilter(SENT));

                    //---when the SMS has been delivered---
                    getCurrentActivity().registerReceiver(new BroadcastReceiver(){
                        @Override
                        public void onReceive(Context arg0, Intent arg1) {
                            switch (getResultCode())
                            {
                                case Activity.RESULT_OK:
                                    try {
                                        jsonObject.put("message", "SMS delivered successfully.");
                                        jsonObject.put("type", "delivered");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }


                                    successCallback.invoke(jsonObject);
                                    break;
                                case Activity.RESULT_CANCELED:
                                    errorCallback.invoke(String.valueOf(Activity.RESULT_CANCELED), "SMS not delivered");
                                    break;
                            }
                        }
                    }, new IntentFilter(DELIVERED));




                    for(int i = 0; i < parts.size(); i++){
                        sentPendingIntents.add(PendingIntent.getBroadcast(reactContext, i, new Intent(SENT), 0));
                        deliveredPendingIntents.add(PendingIntent.getBroadcast(reactContext, i, new Intent(DELIVERED), 0));
                    }




                    smsManager.sendMultipartTextMessage(recipient, null, parts, sentPendingIntents, deliveredPendingIntents);


                }
            }
            @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
        }).check();

    }
}