package com.secspace.lib.common.utils;

import android.content.Context;
import android.os.Build;

import com.secspace.lib.common.env.SEnvironment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Launcher
 *
 * @author lichuanzhi@tiankuan.net
 */
public class ApkHelper {

    private static final String TAG = ApkHelper.class.getSimpleName();

    /**
     * 查找对应版本
     */
    public static String findApkByVersion(Context context, String name) {
        String installPath = SEnvironment.getSystemDirForAssets() + File.separator + name;
        if (Build.VERSION.SDK_INT >= 28) {
            int version = Build.VERSION.SDK_INT;
            InputStream is = null;
            while (version >= 28) {
                String path = SEnvironment.getSystemDirForAssets() + File.separator + version + File.separator + name;
                try {
                    is = context.getAssets().open(path);
                } catch (IOException e) {
                    version--;
                    continue;
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                installPath = path;
                break;
            }
        }
        DebugLog.d(TAG, "name = " + name + ", path = " + installPath);
        return installPath;
    }

    /**
     * 获取缓存路径
     */
    public static String getCacheApkPath(Context context, boolean clone) {
        String apkPath;
        if (clone) {
            apkPath = context.getExternalCacheDir() + File.separator + "cache";
        } else {
            apkPath = context.getCacheDir() + File.separator + "cache";
        }
        return apkPath;
    }
}
