package com.robinpowered.RNMDMManager;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;

// For MDM
import android.app.Activity;
import android.content.RestrictionsManager;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.os.Bundle;
import android.os.Build;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.WritableNativeMap;
import java.util.Map;
import java.util.HashMap;
import javax.annotation.Nullable;

public class RNMobileDeviceManagerModule extends ReactContextBaseJavaModule {
    public static final String MODULE_NAME = "MobileDeviceManager";
    public static final String APP_CONFIG_CHANGED = "react-native-mdm/managedAppConfigDidChange";

    public RNMobileDeviceManagerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        final ReactApplicationContext thisContext = reactContext;

        final RestrictionsManager restrictionsManager = (RestrictionsManager) reactContext.getSystemService(Context.RESTRICTIONS_SERVICE);

        IntentFilter restrictionFilter = new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
        BroadcastReceiver restrictionReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle appRestrictions = restrictionsManager.getApplicationRestrictions();
                WritableNativeMap data = new WritableNativeMap();
                for (String key : appRestrictions.keySet()){
                    data.putString(key, appRestrictions.getString(key));
                }
                if (thisContext.hasActiveCatalystInstance()) {
                    thisContext
                            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                            .emit(APP_CONFIG_CHANGED, data);
                }
            }
        };
        thisContext.registerReceiver(restrictionReceiver,restrictionFilter);
    }

    public boolean enableLockState() {
        if (!isLockState()) {
            Activity activity = getCurrentActivity();
            if (activity == null) {
                return false;
            }
            activity.startLockTask();
            return true;
        }
        return false;
    }

    public boolean disableLockState() {
        if (isLockState()) {
            Activity activity = getCurrentActivity();
            if (activity == null) {
                return false;
            }
            activity.stopLockTask();
            return true;
        }
        return false;
    }

    public boolean isLockStatePermitted() {
        DevicePolicyManager dpm = (DevicePolicyManager)
                getReactApplicationContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
        return dpm.isLockTaskPermitted(getReactApplicationContext().getPackageName());
    }

    public boolean isLockState() {
        boolean isLocked = false;
        ActivityManager am = (ActivityManager) getReactApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            isLocked = am.getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE;
        } else {
            isLocked = am.isInLockTaskMode();
        }
        return isLocked;
    }

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

    @Override
    public @Nullable Map<String, Object> getConstants() {
        HashMap<String, Object> constants = new HashMap<String, Object>();
        constants.put("APP_CONFIG_CHANGED", APP_CONFIG_CHANGED);
        return constants;
    }

    private boolean isMDMSupported() {
        RestrictionsManager restrictionsManager = (RestrictionsManager) getReactApplicationContext().getSystemService(Context.RESTRICTIONS_SERVICE);
        return restrictionsManager.getApplicationRestrictions().size() > 0;
    }

    @ReactMethod
    public void isSupported(final Promise promise) {
        promise.resolve(isMDMSupported());
    }

    @ReactMethod
    public void getConfiguration(final Promise promise) {
        if (isMDMSupported()) {
            RestrictionsManager restrictionsManager = (RestrictionsManager) getReactApplicationContext().getSystemService(Context.RESTRICTIONS_SERVICE);
            Bundle appRestrictions = restrictionsManager.getApplicationRestrictions();
            WritableNativeMap data = new WritableNativeMap();
            for (String key : appRestrictions.keySet()){
                data.putString(key, appRestrictions.getString(key));
            }
            promise.resolve(data);
        } else {
            promise.reject(new Error("Managed App Config is not supported"));
        }
    }

    @ReactMethod
    public void isAutonomousSingleAppModeSupported(final Promise promise) {
        promise.resolve(isLockStatePermitted());
    }

    @ReactMethod
    public void isSingleAppModeEnabled(final Promise promise) {
        try {
          promise.resolve(isLockState());
        } catch (Exception e) {
          promise.reject(e);
        }
    }

    @ReactMethod
    public void isAutonomousSingleAppModeEnabled(final Promise promise) {
        boolean lockedStatus = false;
        ActivityManager am = (ActivityManager) getReactApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                lockedStatus = am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED;
            } else {
                lockedStatus = isLockStatePermitted() && am.isInLockTaskMode();
            }
        } catch (Exception e) {
            promise.reject(e);
        }
        promise.resolve(lockedStatus);
    }

    @ReactMethod
    public void enableAutonomousSingleAppMode(final Promise promise) {
        try {
            promise.resolve(enableLockState());
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void disableAutonomousSingleAppMode(final Promise promise) {
        try {
            promise.resolve(disableLockState());
        } catch (Exception e) {
            promise.reject(e);
        }
    }
}

@@ -3262,33 +3262,373 @@
     
-boolean isLocked = false;
+ActivityManager am = (ActivityManager) getReactApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);%0A%0A        if (Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.M) %7B%0A            return am.getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE;%0A        %7D else %7B%0A            return am.isInLockTaskMode();%0A        %7D%0A    %7D%0A%0A    public boolean isASAM() %7B
 %0A   
@@ -3736,32 +3736,33 @@
 IVITY_SERVICE);%0A
+%0A
         if (Buil
@@ -3815,34 +3815,30 @@
             
-isLocked =
+return
  am.getLockT
@@ -3844,33 +3844,33 @@
 TaskModeState() 
-!
+=
 = ActivityManage
@@ -3878,36 +3878,38 @@
 .LOCK_TASK_MODE_
-NONE
+LOCKED
 ;%0A        %7D else
@@ -3927,18 +3927,40 @@
     
-isLocked =
+return isLockStatePermitted() &&
  am.
@@ -3993,33 +3993,8 @@
   %7D%0A
-        return isLocked;%0A
     
@@ -5874,451 +5874,50 @@
     
-boolean lockedStatus = false;%0A        ActivityManager am = (ActivityManager) getReactApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);%0A        try %7B%0A            if (Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.M) %7B%0A                lockedStatus = am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED;%0A            %7D else %7B%0A                lockedStatus = isLockStatePermitted() && am.isInLockTaskMode();%0A            %7D
+try %7B%0A          promise.resolve(isASAM());
 %0A   
@@ -5937,34 +5937,32 @@
 (Exception e) %7B%0A
-  
           promis
@@ -5988,47 +5988,8 @@
   %7D%0A
-        promise.resolve(lockedStatus);%0A
     

address android issues