
package com.appbundle;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.FileUtils;
import android.preference.PreferenceManager;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;

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

public class RNAppBundlePackage implements ReactPackage {

    private static final String TAG = "RNAppBundleModule";
    private static RNAppBundlePackage mCurrentInstance;
    private String mDocumentsDirectory;
    private Context mContext;

    public static final String PACKAGE_KEY = "appbundle";
    public static final String BUNDLE_FILE = "index.android.bundle";

    public static final String PACK_INFO_KEY = "packInfoKey";
    public static final String LAST_VERSION_KEY = "lastVersion";
    public static final String CURRENT_VERSION_KEY = "currentVersion";
    public static final String PREVIOUS_VERSION_KEY = "previousVersion";
    public static final String IS_FIRST_TIME_KEY = "isFirstTime";
    public static final String IS_FIRST_LOAD_OK_KEY = "isFirstLoadOk";


    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(new RNAppBundleModule(reactContext));
    }

    // Deprecated from RN 0.47
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    public RNAppBundlePackage(Context context) {
        mCurrentInstance = this;
        mContext = context;
        mDocumentsDirectory = context.getFilesDir().getAbsolutePath();
        Log.e(TAG, "RNAppBundleModule: " + mDocumentsDirectory);
    }

    public static String bundleURL() {
        if (mCurrentInstance != null) {

            SharedPreferences prefs = mCurrentInstance.mContext
                    .getSharedPreferences("RNAppBundle", Context.MODE_PRIVATE);
            String packInfoJson = prefs.getString(PACK_INFO_KEY, "{}");

            try {
                JSONObject packInfo = new JSONObject(packInfoJson);
                JSONObject curVersion = packInfo.optJSONObject(CURRENT_VERSION_KEY);
                boolean isFirstTime = packInfo.optBoolean(IS_FIRST_TIME_KEY);
                boolean isFirstLoadOK = packInfo.optBoolean(IS_FIRST_LOAD_OK_KEY);

                // 处理回滚逻辑
                boolean needRollback = (!isFirstTime && !isFirstLoadOK);
                if (needRollback) {
                    curVersion = rollback();
                } else if (isFirstTime) {
                    // 更新首次标记状态
                    prefs.edit()
                            .putString(PACK_INFO_KEY, packInfo.put(IS_FIRST_TIME_KEY, false).toString())
                            .apply();
                }

                if (curVersion != null) {
                    String version = curVersion.getString("version");
                    int bundle = curVersion.getInt("bundle");
                    File packagePath = getPackageForVersion(version, bundle);
                    File bundleFile = new File(packagePath, BUNDLE_FILE);

                    String appVersion = getAppVersionName();
                    if (bundleFile.exists() && appVersion.equals(version)) {
                        return bundleFile.getAbsolutePath();
                    }
                }
            } catch (JSONException e) {
                Log.e("AppBundleUpdate", "解析包信息失败", e);
            }
        }
        Log.e(TAG, "bundleURL: 没有更新" );
        return "assets://" + "index.android.bundle";
    }

    public static JSONObject rollback() {
        SharedPreferences prefs = mCurrentInstance.mContext
                .getSharedPreferences("RNAppBundle", Context.MODE_PRIVATE);
        String packInfoJson = prefs.getString(PACK_INFO_KEY, "{}");
        try {
            JSONObject newInfo = new JSONObject(packInfoJson);
            // 交换当前版本和上一个版本
            if (newInfo.has(PREVIOUS_VERSION_KEY)) {
                Object previousVer = newInfo.get(PREVIOUS_VERSION_KEY);
                newInfo.put(CURRENT_VERSION_KEY, previousVer);
            }

            // 更新状态标志
            newInfo.put(IS_FIRST_TIME_KEY, false);
            newInfo.put(IS_FIRST_LOAD_OK_KEY, true);

            // 保存修改
            prefs.edit()
                    .putString(PACK_INFO_KEY, newInfo.toString())
                    .apply();

            return newInfo.getJSONObject(CURRENT_VERSION_KEY);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static JSONObject getBundleInfoForPath(String path) {
        File bundleVersionFile = new File(path, "bundleVersion.json");
        if (bundleVersionFile.exists()) {
            return readFile(bundleVersionFile);
        }
        return null;
    }

    private static JSONObject readFile(File file) {
        try {
            InputStream is = new FileInputStream(file);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String fileContent = new String(buffer, "UTF-8");
            JSONObject jsonObject = new JSONObject(fileContent);
            return jsonObject;
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAppVersionName() {
        try {
            PackageInfo packageInfo = mCurrentInstance.mContext.getPackageManager().getPackageInfo(mCurrentInstance.mContext.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static File getPackageForVersion(String version, int bundle) {
        // 获取应用支持目录（对应 iOS 的 NSApplicationSupportDirectory）
        File appSupportDir = new File(mCurrentInstance.mContext.getFilesDir(), PACKAGE_KEY);

        // 构建版本路径：appbundle/version/bundle
        return new File(new File(appSupportDir, version), String.valueOf(bundle));
    }

    public static File getCurrentPackPath() {
        SharedPreferences prefs = mCurrentInstance.mContext
                .getSharedPreferences("RNAppBundle", Context.MODE_PRIVATE);
        String packInfoJson = prefs.getString(PACK_INFO_KEY, null);

        if (packInfoJson != null) {
            try {
                JSONObject packInfo = new JSONObject(packInfoJson);
                JSONObject bundleInfo = packInfo.getJSONObject(CURRENT_VERSION_KEY);

                String version = bundleInfo.getString("version");
                int bundle = bundleInfo.getInt("bundle");
                return getPackageForVersion(version, bundle);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String appendPathComponent(String basePath, String appendPathComponent) {
        return new File(basePath, appendPathComponent).getAbsolutePath();
    }

}