package com.supersami.foregroundservice;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import com.supersami.foregroundservice.CustomKeyguardDismissCallback;
import android.content.Intent;
import android.app.NotificationManager;
import android.app.KeyguardManager;
import android.view.View;
import android.os.LocaleList;
import android.graphics.PixelFormat;
import android.widget.EditText;
import android.view.WindowManager;
import android.view.Gravity;
import android.widget.Button;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.WindowManager;
import android.os.Build;
import android.os.PowerManager;
import com.facebook.react.bridge.Callback;
import android.util.Log;
import androidx.annotation.RequiresApi;
import android.app.Activity;
import android.content.Context;
import android.app.KeyguardManager.KeyguardLock;
import android.app.KeyguardManager.KeyguardDismissCallback;
import android.widget.Toast;
import com.facebook.react.bridge.Arguments;
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 java.util.Locale;
import static com.supersami.foregroundservice.Constants.ERROR_INVALID_CONFIG;
import static com.supersami.foregroundservice.Constants.ERROR_SERVICE_ERROR;
import static com.supersami.foregroundservice.Constants.NOTIFICATION_CONFIG;
import static com.supersami.foregroundservice.Constants.TASK_CONFIG;
import android.telephony.SubscriptionInfo;
import android.telephony.TelephonyManager;
import android.telephony.SubscriptionManager;
import android.app.usage.NetworkStats;
import android.net.ConnectivityManager;
import android.app.usage.NetworkStatsManager;
import android.os.Process;
import java.util.List;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import androidx.core.content.FileProvider;
import java.io.*;

public class ForegroundServiceModule extends ReactContextBaseJavaModule {

    private final ReactApplicationContext reactContext;

    public ForegroundServiceModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }
    String deviceName = Build.MODEL;
    WindowManager windowManager;
    WindowManager.LayoutParams params;
    Button overlayButton;

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

    private boolean isRunning(){
        // Get the ForegroundService running value
        ForegroundService instance = ForegroundService.getInstance();
        int res = 0;
        if(instance != null){
            res = instance.isRunning();
        }
        return res > 0;
    }


    @ReactMethod
    public void startService(ReadableMap notificationConfig, Promise promise) {
        if (notificationConfig == null) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: Notification config is invalid");
            return;
        }

        if (!notificationConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG , "ForegroundService: id is required");
            return;
        }

        if (!notificationConfig.hasKey("title")) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: title is reqired");
            return;
        }

        if (!notificationConfig.hasKey("message")) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: message is required");
            return;
        }

        try{
            Intent intent = new Intent(getReactApplicationContext(), ForegroundService.class);
            intent.setAction(Constants.ACTION_FOREGROUND_SERVICE_START);
            intent.putExtra(NOTIFICATION_CONFIG, Arguments.toBundle(notificationConfig));
            ComponentName componentName = getReactApplicationContext().startService(intent);

            if (componentName != null) {
                promise.resolve(null);
            } else {
                promise.reject(ERROR_SERVICE_ERROR, "ForegroundService: Foreground service failed to start.");
            }
        }
        catch(IllegalStateException e){
            promise.reject(ERROR_SERVICE_ERROR, "ForegroundService: Foreground service failed to start.");
        }
    }

    @ReactMethod
    public void updateNotification(ReadableMap notificationConfig, Promise promise) {
        if (notificationConfig == null) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: Notification config is invalid");
            return;
        }

        if (!notificationConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG , "ForegroundService: id is required");
            return;
        }

        if (!notificationConfig.hasKey("title")) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: title is reqired");
            return;
        }

        if (!notificationConfig.hasKey("message")) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: message is required");
            return;
        }

        try{

            Intent intent = new Intent(getReactApplicationContext(), ForegroundService.class);
            intent.setAction(Constants.ACTION_UPDATE_NOTIFICATION);
            intent.putExtra(NOTIFICATION_CONFIG, Arguments.toBundle(notificationConfig));
            ComponentName componentName = getReactApplicationContext().startService(intent);

            if (componentName != null) {
                promise.resolve(null);
            } else {
                promise.reject(ERROR_SERVICE_ERROR, "Update notification failed.");
            }
        }
        catch(IllegalStateException e){
            promise.reject(ERROR_SERVICE_ERROR, "Update notification failed, service failed to start.");
        }
    }

    // helper to dismiss a notification. Useful if we used multiple notifications
    // for our service since stopping the foreground service will only dismiss one notification
    @ReactMethod
    public void cancelNotification(ReadableMap notificationConfig, Promise promise) {
        if (notificationConfig == null) {
            promise.reject(ERROR_INVALID_CONFIG, "ForegroundService: Notification config is invalid");
            return;
        }

        if (!notificationConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG , "ForegroundService: id is required");
            return;
        }

        try{
            int id = (int)notificationConfig.getDouble("id");

            NotificationManager mNotificationManager=(NotificationManager)this.reactContext.getSystemService(this.reactContext.NOTIFICATION_SERVICE);
            mNotificationManager.cancel(id);

            promise.resolve(null);
        }
        catch(Exception e){
            promise.reject(ERROR_SERVICE_ERROR, "Failed to cancel notification.");
        }
    }

    @ReactMethod
    public void stopService(Promise promise) {

        // stop main service
        Intent intent = new Intent(getReactApplicationContext(), ForegroundService.class);
        intent.setAction(Constants.ACTION_FOREGROUND_SERVICE_STOP);

        //getReactApplicationContext().stopService(intent);

        // Looks odd, but we do indeed send the stop flag with a start command
        // if it fails, use the violent stop service instead
        try{
            getReactApplicationContext().startService(intent);
            promise.resolve("stopped");
        }
        catch(IllegalStateException e){
            try{
                getReactApplicationContext().stopService(intent);
                promise.resolve("stopped");
            }
            catch(Exception e2){
                promise.reject(ERROR_SERVICE_ERROR, "Service stop failed: " + e2.getMessage());
                return;
            }
        }

        // Also stop headless tasks, should be noop if it's not running.
        // TODO: Not working, headless task must finish regardless. We have to rely on JS code being well done.
        // intent = new Intent(getReactApplicationContext(), ForegroundServiceTask.class);
        // getReactApplicationContext().stopService(intent);

        promise.resolve(null);
    }

    Handler handler = new Handler(Looper.getMainLooper());
    Runnable checkOverlaySetting = new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                return;
            }
            if (Settings.canDrawOverlays(reactContext)) {
                try {
                    Intent launchIntent = getCurrentActivity().getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    if (launchIntent != null) {
                        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getCurrentActivity().startActivity(launchIntent);
                        Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (Exception e) {
                    Intent i = reactContext.getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    reactContext.startActivity(i);
                    Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            handler.postDelayed(this, 800);
        }
    };


    Runnable checkBatteryOptimized = new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                return;
            }
            if (isBatteryOptimizationIgnored()) {
                try {
                    Intent launchIntent = getCurrentActivity().getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    if (launchIntent != null) {
                        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getCurrentActivity().startActivity(launchIntent);
                        Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (Exception e) {
                    Intent i = reactContext.getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    reactContext.startActivity(i);
                    Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            handler.postDelayed(this, 800);
        }
    };

    Runnable checkCanInstallPackages = new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                return;
            }
            if (canInstallPackages()) {
                try {
                    Intent launchIntent = getCurrentActivity().getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    if (launchIntent != null) {
                        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getCurrentActivity().startActivity(launchIntent);
                        Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (Exception e) {
                    Intent i = reactContext.getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    reactContext.startActivity(i);
                    Toast.makeText(reactContext, "Permission granted", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            handler.postDelayed(this, 800);
        }
    };

    @ReactMethod
    public void requestOverlayPermission(Promise promise) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this.reactContext)) {
                    if ("xiaomi".equals(Build.MANUFACTURER.toLowerCase(Locale.ROOT))) {
                        final Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
                        intent.putExtra("extra_pkgname", this.reactContext.getPackageName());
                        this.reactContext.startActivityForResult(intent, 0, null);
                    } else {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + this.reactContext.getPackageName()));
                        this.reactContext.startActivityForResult(intent, 0, null);
                    }
                    handler.postDelayed(checkOverlaySetting, 800);
                }
            } else {
                promise.resolve(true);
            }
        } catch (Error e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void requestBatteryOptimizationWhitelist(Promise promise) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!isBatteryOptimizationIgnored()) {
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + this.reactContext.getPackageName()));
                    this.reactContext.startActivityForResult(intent, 0, null);
                    handler.postDelayed(checkBatteryOptimized, 800);
                }
            } else {
                promise.resolve(true);
            }
        } catch (Error e) {
            promise.reject(e);
        }
    }

    public boolean isBatteryOptimizationIgnored() {
        PowerManager powerManager = (PowerManager) this.reactContext.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            return powerManager.isIgnoringBatteryOptimizations(this.reactContext.getPackageName());
        }
        return false;
    }

    public boolean canInstallPackages() {
        Context context = this.reactContext.getApplicationContext();
        if (!context.getPackageManager().canRequestPackageInstalls()) {
            return true;
        } else {
            return false;
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @ReactMethod
    public void isRequestOverlayPermissionGranted(Callback booleanCallback) {
        boolean equal = !Settings.canDrawOverlays(this.reactContext);
        booleanCallback.invoke(equal);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @ReactMethod
    public void isBatteryOptimizationGranted(Callback booleanCallback) {
        PowerManager powerManager = (PowerManager) this.reactContext.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            booleanCallback.invoke(powerManager.isIgnoringBatteryOptimizations(this.reactContext.getPackageName()));
        } else {
            booleanCallback.invoke(false);
        }
    }

    @ReactMethod
    public void isLocaleGreek(Callback booleanCallback) {
        boolean isLocaleGreek = false;
        if(!(deviceName.equals("E600M") || Build.BRAND.equals("PAX") || Build.BRAND.equals("SUNMI"))){
            booleanCallback.invoke(true);
        } else {
            LocaleList availableLocales = Resources.getSystem().getConfiguration().getLocales();
            for (int i = 0; i < availableLocales.size(); i++) {
                Log.d("locallee", availableLocales.get(i).getLanguage());
                if (availableLocales.get(i).getLanguage().equals("el")) {
                    isLocaleGreek = true;
                }
            }
            booleanCallback.invoke(isLocaleGreek);
        }
    }
    public boolean isGreekLocaleAvailable() {
        LocaleList availableLocales = Resources.getSystem().getConfiguration().getLocales();
        for (int i = 0; i < availableLocales.size(); i++) {
            if (availableLocales.get(i).getLanguage().equals("el")) {
                return true;
            }
        }
        return false;
    }
    @ReactMethod
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getNetworkUsage(String startDate, String endDate, Boolean wifi, Promise promise) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            if (start == null || end == null) {
                promise.reject("Invalid date format");
                return;
            }
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(start);
            startCalendar.set(Calendar.HOUR_OF_DAY, 0);
            startCalendar.set(Calendar.MINUTE, 0);
            startCalendar.set(Calendar.SECOND, 1);
            startCalendar.set(Calendar.MILLISECOND, 0);
            long startTime = startCalendar.getTimeInMillis();
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(end);
            endCalendar.set(Calendar.HOUR_OF_DAY, 23);
            endCalendar.set(Calendar.MINUTE, 59);
            endCalendar.set(Calendar.SECOND, 59);
            endCalendar.set(Calendar.MILLISECOND, 999);
            long endTime = endCalendar.getTimeInMillis();
            int appUid = Process.myUid();
            NetworkStatsManager networkStatsManager = (NetworkStatsManager) this.reactContext.getSystemService(this.reactContext.NETWORK_STATS_SERVICE);
            if (networkStatsManager == null) {
                promise.reject("NetworkStatsManager is null");
                return;
            }
            NetworkStats networkStats = networkStatsManager.queryDetailsForUid(wifi == true ? ConnectivityManager.TYPE_WIFI : ConnectivityManager.TYPE_MOBILE, null, startTime, endTime, appUid);
            NetworkStats.Bucket bucket = new NetworkStats.Bucket();
            long totalRxBytes = 0;
            long totalTxBytes = 0;
            while (networkStats.hasNextBucket()) {
                networkStats.getNextBucket(bucket);
                totalRxBytes += bucket.getRxBytes();
                totalTxBytes += bucket.getTxBytes();
            }
            networkStats.close();
            double totalRxMB = totalRxBytes / (1024.0 * 1024.0);
            double totalTxMB = totalTxBytes / (1024.0 * 1024.0);
            double totalUsage = (totalRxBytes + totalTxBytes) / (1024.0 * 1024.0);
            WritableMap result = new WritableNativeMap();
            result.putString("download", String.format(Locale.getDefault(), "%.2f MB", totalRxMB));
            result.putString("upload", String.format(Locale.getDefault(), "%.2f MB", totalTxMB));
            result.putString("totalUsage", String.format(Locale.getDefault(), "%.2f MB", totalUsage));
            promise.resolve(result);
        } catch (Exception e) {
            promise.reject("Error fetching cellular data usage");
        }
    }

    @ReactMethod
    public void showGreekLanguageButton(Promise promise) {
        Handler checkLocaleHandler = new Handler();
        final Runnable[] checkLocaleRunnable = new Runnable[1];
        windowManager = (WindowManager) reactContext.getSystemService(reactContext.WINDOW_SERVICE);
        Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
        getCurrentActivity().startActivity(intent);
        checkLocaleRunnable[0] = new Runnable() {
            @Override
            public void run() {
                if (isGreekLocaleAvailable()) {
                    try {
                        Intent launchIntent = reactContext.getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                        if (launchIntent != null) {
                            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            getCurrentActivity().startActivity(launchIntent);
                            Toast.makeText(reactContext, "Greek Language Added", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (Exception e) {
                        Intent i = reactContext.getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        getCurrentActivity().startActivity(i);
                        Toast.makeText(reactContext, "Greek Language Added", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    // Stop checking since the user has already switched to Greek
                    checkLocaleHandler.removeCallbacks(checkLocaleRunnable[0]);
                } else {
                    // Continue checking
                    checkLocaleHandler.postDelayed(this, 800);
                }
            }
        };
        checkLocaleHandler.post(checkLocaleRunnable[0]);
        promise.resolve("Button Shown");
    }


    @ReactMethod
    public void openApplication(Promise promise) {

        try {
            Intent launchIntent = getCurrentActivity().getPackageManager().getLaunchIntentForPackage(reactContext.getPackageName());
            if (launchIntent != null) {
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getCurrentActivity().startActivity(launchIntent);
                promise.resolve("App is Opened");
            } else {
                promise.resolve("App not Opened");
            }
        } catch (Exception e) {
            promise.resolve("App not Opened");
        }
    }

    @ReactMethod
    public void openOtherApplication(String packageName, Promise promise) {
        PackageManager pm = this.reactContext.getPackageManager();
        try {
            this.reactContext.startActivity(pm.getLaunchIntentForPackage(packageName));
        } catch (Exception e) {
            promise.reject(e);
        }
    }
    @ReactMethod
    public void isPackageInstalled(String packageName, Callback cb) {
        PackageManager pm = this.reactContext.getPackageManager();
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            cb.invoke(true);
        } catch (Exception e) {
            cb.invoke(false);
        }
    }

    @ReactMethod
    public void unlockScreen(Promise promise) {

        try {
            Context context = getReactApplicationContext();
            // Acquire a wake lock to wake up the screen
            PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
            wakeLock.acquire();
            // Only for PAX
            KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            Log.d("keyguardetame",""+keyguardManager.isDeviceLocked() + " ," + keyguardManager.isKeyguardSecure());
            KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
            if(keyguardManager.isDeviceLocked() == true && keyguardManager.isKeyguardSecure() == true){
                promise.resolve("Device is Secure");
                return;
            }
            keyguardLock.disableKeyguard();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CustomKeyguardDismissCallback mockCallback = new CustomKeyguardDismissCallback();
                if(getCurrentActivity() == null){
                    promise.resolve("App is not opened. Continue launch app.");
                    return;
                } else {
                    keyguardManager.requestDismissKeyguard(getCurrentActivity(), mockCallback);
                }
            } else {
                // API < 26: nothing more we can do beyond disableKeyguard()
                promise.resolve("Unlock attempted for API < 26");
            }
            wakeLock.release();
            promise.resolve(null);
        } catch (Exception e) {
            // Handle exceptions
            promise.resolve("Device is Secure");
            Log.d("keyguardetame",e.getMessage());
        }
    }

    @ReactMethod
    public void installApk(String apkPath, Promise promise) {
        File apkFile = new File(apkPath);
        if (!apkFile.exists()) return;

        Context context = reactContext.getApplicationContext();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!context.getPackageManager().canRequestPackageInstalls()) {
                Intent intent2 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                        Uri.parse("package:" + context.getPackageName()));
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent2);
                handler.postDelayed(checkCanInstallPackages, 800);
                promise.resolve("User needs to accept permissions.");
                return;
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", apkFile);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            apkUri = Uri.fromFile(apkFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
        promise.resolve("Application Update initiated successfully!");
    }

    @ReactMethod
    public void stopServiceAll(Promise promise) {

        // stop main service with all action
        Intent intent = new Intent(getReactApplicationContext(), ForegroundService.class);
        intent.setAction(Constants.ACTION_FOREGROUND_SERVICE_STOP_ALL);

        try{
            getReactApplicationContext().startService(intent);
        }
        catch(IllegalStateException e){
            try{
                getReactApplicationContext().stopService(intent);
            }
            catch(Exception e2){
                promise.reject(ERROR_SERVICE_ERROR, "Service stop all failed: " + e2.getMessage());
                return;
            }
        }

        promise.resolve(null);
    }

    @ReactMethod
    public void runTask(ReadableMap taskConfig, Promise promise) {

        if (!taskConfig.hasKey("taskName")) {
            promise.reject(ERROR_INVALID_CONFIG, "taskName is required");
            return;
        }

        if (!taskConfig.hasKey("delay")) {
            promise.reject(ERROR_INVALID_CONFIG, "delay is required");
            return;
        }

        try{
            Intent intent = new Intent(getReactApplicationContext(), ForegroundService.class);
            intent.setAction(Constants.ACTION_FOREGROUND_RUN_TASK);
            intent.putExtra(TASK_CONFIG, Arguments.toBundle(taskConfig));

            ComponentName componentName = getReactApplicationContext().startService(intent);

            if (componentName != null) {
                promise.resolve(null);
            } else {
                promise.reject(ERROR_SERVICE_ERROR, "Failed to run task: Service did not start");
            }
        }
        catch(IllegalStateException e){
            promise.reject(ERROR_SERVICE_ERROR, "Failed to run task: Service did not start");
        }
    }

    @ReactMethod
    public void isRunning(Promise promise) {

        // Get the ForegroundService running value
        ForegroundService instance = ForegroundService.getInstance();
        int res = 0;
        if(instance != null){
            res = instance.isRunning();
        }

        promise.resolve(res);
    }



    @ReactMethod
    public void getShouldRestart(Promise promise) {
        ForegroundService instance = ForegroundService.getInstance();
        int res = 1;
        if(instance != null){
            res = instance.getShouldRestart();
        }

        promise.resolve(res);
    }
    @ReactMethod
    public void setIntentListener(Integer status, Promise promise) {
        ForegroundService instance = ForegroundService.getInstance();
        if(instance != null){
            instance.setIntentListenerReady(status);
        }
        promise.resolve(null);
    }



}
