package io.layers.sdk.reactnative;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

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

/**
 * Native module providing device info that is not accessible from JS.
 */
public class LayersDeviceInfoModule extends ReactContextBaseJavaModule {

    public LayersDeviceInfoModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

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

    @ReactMethod
    public void getAppVersion(Promise promise) {
        try {
            PackageInfo pInfo = getReactApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(getReactApplicationContext().getPackageName(), 0);
            promise.resolve(pInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            promise.resolve(null);
        }
    }

    /**
     * Returns the timestamp (milliseconds since epoch) when the app was first
     * installed, as reported by the package manager. Used for install event
     * gating: if the app was installed more than 24 hours ago and the SDK has
     * never run before, suppress is_first_launch on the first app_open event.
     */
    @ReactMethod
    public void getFirstInstallTime(Promise promise) {
        try {
            PackageInfo pInfo = getReactApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(getReactApplicationContext().getPackageName(), 0);
            promise.resolve((double) pInfo.firstInstallTime);
        } catch (PackageManager.NameNotFoundException e) {
            promise.resolve(null);
        }
    }
}
