
package com.reactlibrary;

import android.support.annotation.Nullable;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.reactlibrary.bean.UpdateBean;
import com.reactlibrary.bundle.CreateFileUtil;
import com.reactlibrary.bundle.DecompressionInitBundleZipUtil;
import com.reactlibrary.constant.Constant;
import com.reactlibrary.util.BundleInfoUtil;
import com.reactlibrary.util.RnBundleUtil;

import org.json.JSONException;
import org.json.JSONObject;


public class RNReactNativeSunsoftBundleTest2Module extends ReactContextBaseJavaModule {

  private final ReactApplicationContext reactContext;
  private static final String BUNDLE_EVENT_NAME = "bundleevent";
  private String upadteTag = "";
  public RNReactNativeSunsoftBundleTest2Module(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }



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

  @ReactMethod
  public void startInitUnZipBundle(){
    if (reactContext == null){
      System.out.println("bundle初始化解压reactContext为空");
      return;
    }
    try {
      DecompressionInitBundleZipUtil.decompressionInitBundleZip(reactContext);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("bundle初始化解压异常"+e.toString());
    }
  }



  @ReactMethod
  public void startBundleUpdate(ReadableMap bundleJson,final Promise promise){
    System.out.println("Rn---------------------Rn传值过来了哈哈哈哈哈哈哈哈哈");
    if (reactContext == null){
      System.out.println("bundle更新reactContext为空");
      return;
    }
    CreateFileUtil.setContext(reactContext);

    try {
      if (bundleJson == null) {
        System.out.println("bundle更新传递参数为空");
        return;
      }

      JSONObject jsonObject = new JSONObject(bundleJson.toString());
      if (jsonObject.has("NativeMap")) {
        JSONObject jsonObject1 = jsonObject.getJSONObject("NativeMap");
        UpdateBean updateBean = new UpdateBean();
        if (jsonObject1.has("url")) {
          updateBean.setUrl(jsonObject1.getString("url"));
        }

        if (jsonObject1.has("bundleName")) {
          updateBean.setBundleName(jsonObject1.getString("bundleName"));
        }

        if (jsonObject1.has("versionName")) {
          updateBean.setVersionName(jsonObject1.getString("versionName"));
        }

        if (jsonObject1.has("bundleCode")) {
          updateBean.setBundleCode(jsonObject1.getString("bundleCode"));
        }


        if (jsonObject1.has("hashCodeStr")) {
          updateBean.setHashCodeStr(jsonObject1.getString("hashCodeStr"));
        }

        if (jsonObject1.has("isincrement")) {
          updateBean.setIsincrement(jsonObject1.getString("isincrement"));
          upadteTag = updateBean.getIsincrement();
        }

        if (jsonObject1.has("isUpdate")) {
          updateBean.setIsUpdate(jsonObject1.getString("isUpdate"));
        }

        CreateFileUtil.creatSingleFile(Constant.BUNDLE_FILE_NAME);
        CreateFileUtil.creatSingleFile(Constant.BUNDLE_ZIP_FILE_NAME);
        CreateFileUtil.creatSingleFile("usebundle");
        RnBundleUtil.downLoadBundleZip(reactContext,updateBean, new RnBundleUtil.IUpdateBundleListener() {
          @Override
          public void updateSuccess(String tag) {
              //更新成功
//            updateResult(tag,"0");
            WritableMap map = Arguments.createMap();
            map.putString("type", tag);
            map.putString("result","0");
            promise.resolve(map);
          }

          @Override
          public void updateError(String tag) {
              //更新失败
//            updateResult(tag,"1");
            WritableMap map = Arguments.createMap();
            map.putString("type", tag);
            map.putString("result","1");
            promise.resolve(map);
          }
        });
      }
    } catch (JSONException e) {
      e.printStackTrace();
      System.out.println("bundle更新传递参数通信异常");
//      updateResult(upadteTag,"1");
      WritableMap map = Arguments.createMap();
      map.putString("type", "1");
      map.putString("result","1");
      promise.resolve(map);
    }
  }


  /**
   * @param  type 0全量更新，1增量更新
   * @param  result 0 成功，1失败
   *
     */
  @ReactMethod
  private void updateResult(String type,String result) {
    WritableMap map = Arguments.createMap();
    map.putString("type", type);
    map.putString("result",type);
    sendEvent(getReactApplicationContext(), BUNDLE_EVENT_NAME, map);
  }

  @ReactMethod
  private void sendEvent(ReactContext reactContext,
                         String eventName,
                         @Nullable WritableMap params) {
    reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
  }

  /*
  * 重新加载bundle文件*/
  @ReactMethod
  public void reloadBundle(){
       BundleInfoUtil.bundleUpdateDone(reactContext);
  }

}