package com.cmcm.crashhandler;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;

import com.facebook.react.ReactApplication;
import com.facebook.react.bridge.ReactContext;

import static android.content.ContentValues.TAG;

/***
 ** @author nieyihe
 ** @email nieyihe@cmcm.com
 ** @date 2019/4/17
 **/
public class AutoStartHelper {

    public static void doRestartNativeEnvironment(Context c) {
        try {
            if (c != null) {
                PackageManager pm = c.getPackageManager();
                if (pm != null) {
                    Intent mStartActivity = pm.getLaunchIntentForPackage(
                            c.getPackageName()
                    );
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        int mPendingIntentId = 654311;
                        PendingIntent mPendingIntent = PendingIntent
                                .getActivity(c, mPendingIntentId, mStartActivity,
                                        PendingIntent.FLAG_CANCEL_CURRENT);
                        AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                        System.exit(0);
                    } else {
                        throw new Exception("Was not able to restart application, mStartActivity null");
                    }
                } else {
                    throw new Exception("Was not able to restart application, PM null");
                }
            } else {
                throw new Exception("Was not able to restart application, Context null");
            }
        } catch (Exception ex) {
            Log.e(TAG, "Was not able to restart application");
        }
    }

    public static void doRestartJSEnvironment(ReactContext context) {
        ((ReactApplication)(context.getCurrentActivity().getApplication())).getReactNativeHost().getReactInstanceManager().recreateReactContextInBackground();
    }
}
