package com.rnboat.framework.base;

import android.app.Application;

import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.common.LifecycleState;
//import com.qianmi.qmlogger.QMLog;

import java.util.Collections;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Created by Castiel on 2018/3/31.
 */

public class RNBoatReactNativeHost extends ReactNativeHost {
    private static String TAG = "RNBoatReactNativeHost";

    private String mJSBundleFile;
    private String mBundleAssetName;
    private final Application mApplication;

    protected RNBoatReactNativeHost(Application application, String jsBundleFile, String bundleAssetName) {
        super(application);
        mApplication = application;
        mJSBundleFile = jsBundleFile;
        mBundleAssetName = bundleAssetName;
    }

    @Override
    protected ReactInstanceManager createReactInstanceManager() {
        ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
                .setApplication(mApplication)
                .setJSMainModuleName(getJSMainModuleName())
                .setUseDeveloperSupport(getUseDeveloperSupport())
                .setRedBoxHandler(getRedBoxHandler())
                .setUIImplementationProvider(getUIImplementationProvider())
                .setInitialLifecycleState(LifecycleState.BEFORE_CREATE);

        for (ReactPackage reactPackage : getPackages()) {
            builder.addPackage(reactPackage);
        }

        String jsBundleFile = getJSBundleFile();
        if (jsBundleFile != null) {
            builder.setJSBundleFile(jsBundleFile);
        } else {
            builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName()));
        }
        return builder.build();
    }

    @Override
    public boolean getUseDeveloperSupport() {
        return false;
    }

    @Override
    protected List<ReactPackage> getPackages() {
        if (mApplication instanceof RNBoatApplication) {
            return ((RNBoatApplication) mApplication).getPackages();
        }
//        QMLog.e(TAG, "main application must be implements RNBoatApplication");
        return Collections.emptyList();
    }

    @Nullable
    @Override
    protected String getJSBundleFile() {
        return mJSBundleFile;
    }

    @Nullable
    @Override
    protected String getBundleAssetName() {
        return mBundleAssetName;
    }
}
