package com.moonmiles.bridge.apm.abs;

import android.content.Context;
import android.util.Log;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.moonmiles.apm.sdk.APM;
import com.moonmiles.apm.sdk.APMPublic;
import com.moonmiles.bridge.apm.APMConstants;
import com.moonmiles.bridge.apm.utils.APMBridgeUtils;

/**
 * Created by Vincent on 16/10/2017.
 */

public abstract class APMReactContextBaseJavaModule extends ReactContextBaseJavaModule
{
    public APMReactContextBaseJavaModule(ReactApplicationContext reactContext)
    {
        super(reactContext);
    }

    protected APM getAPM()
    {
        return getAPM(null);
    }

    protected APM getAPM(Promise promise)
    {
        APM apm = null;

        Context context = getContextFromModule(promise);
        if(context != null)
            apm = APMPublic.sharedInstance(context);

        return apm;
    }

    protected Context getContextFromModule()
    {
        return getContextFromModule(null);
    }

    protected Context getContextFromModule(Promise promise)
    {
        Context context = APMBridgeUtils.getContextFromModule(getReactApplicationContext(), getCurrentActivity());

        if(context == null && promise != null)
        {
            Log.w(APMConstants.TAG, "Promise reject with ERROR_NO_CONTEXT");
            promise.reject(APMConstants.ERROR_NO_CONTEXT, APMConstants.MESSAGE_ERROR_NO_CONTEXT);
        }

        return context;
    }
}
