package com.gh.gamecenter.core.utils;

import android.content.res.AssetManager;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gh.gamecenter.core.HaloApp;
import com.lightgame.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

@Keep
public class PluginRedirectHelper {

    private static final String ASSET_DIR = "/redirected_plugin/";

    private static final String TAG = "PluginRedirectHelper";

    public static @Nullable String[] listAsset(AssetManager am, String path) {
        try {
            String[] assets = am.list(path);

            Utils.log(TAG, "listAsset: path " + path);

            // 欺骗 QQ 小游戏 SDK，让其以为 assets 里有 gdtadv2.jar
            if ((assets == null || assets.length == 0)
                    && "gdt_plugin".equals(path)) {
                assets = new String[1];
                assets[0] = "gdtadv2.jar";
            }

            Utils.log(TAG, "listAsset: return " + Arrays.toString(assets));

            return assets;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getAssetDir() {
        String dir = HaloApp.getInstance().getFilesDir() + ASSET_DIR;
        File dirFile = new File(dir);

        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return HaloApp.getInstance().getFilesDir() + ASSET_DIR;
    }

    public static InputStream openAsset(AssetManager am, String fileName) throws FileNotFoundException {
        try {
            // 先加载apk包中的asset文件
            Utils.log(TAG, "openAsset: " + fileName + " load from asset");

            return am.open(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // apk包中的 asset 文件加载失败时加载动态下发的 asset 文件
        Utils.log(TAG, "openAsset: " + fileName + " load from redirected path");

        String assetPath = findAsset(fileName);

        return new FileInputStream(assetPath);
    }

    private static String findAsset(String assetName) {
        File dir = new File(getAssetDir());

        Utils.log(TAG, "findAsset: " + assetName + " in " + dir.getAbsolutePath());

        File assetFile = new File(dir, assetName);

        if (assetFile.exists()) {
            Utils.log(TAG, "findAsset: " + " found " +  assetName + " in " + dir.getAbsolutePath());
        }

        return assetFile.getAbsolutePath();
    }

}
