package com.bohuikeji.frame.module.admin.utils;

import android.content.res.AXmlResourceParser;
import android.util.TypedValue;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.frame.module.admin.entity.util.ApkInfo;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * @author Admin
 */
public class ApkUtils {

    private static final float RADIX_MULTS[] = {0.00390625F, 3.051758E-005F, 1.192093E-007F, 4.656613E-010F};

    private static final String DIMENSION_UNITS[] = {"px", "dip", "sp", "pt", "in", "mm", "", ""};

    private static final String FRACTION_UNITS[] = {"%", "%p", "", "", "", "", "", ""};


    /**
     * 获取热更新包信息
     * @param file
     * @return
     */
    public static ApkInfo getWgtInfo(File file){
        ApkInfo apkInfo=new ApkInfo();
        InputStream stream=getZipNodeCont(file,"manifest.json");
        JSONObject res=null;
        try {
            res=JSON.parseObject(stream, JSONObject.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        apkInfo.setAppName(res.getString("name"));
        apkInfo.setVersionName(res.getJSONObject("version").getString("name"));
        apkInfo.setVersionCode(res.getJSONObject("version").getInteger("code"));
        return apkInfo;
    }

    /**
     * 获取apk信息
     * @param file
     * @return
     */
    public static ApkInfo getApkInfo(File file){
        ApkInfo apkInfo=new ApkInfo();
        ApkMeta apkMeta= null;
        try {
            apkMeta= new ApkFile(file).getApkMeta();
        } catch (IOException e) {
            e.printStackTrace();
        }
        apkInfo.setAppName(apkMeta.getLabel());
        apkInfo.setVersionCode(Math.toIntExact(apkMeta.getVersionCode()));
        apkInfo.setVersionName(apkMeta.getVersionName());
        apkInfo.setPackageName(apkMeta.getPackageName());
        return apkInfo;
    }



    /**
     * 获取apk信息
     * @return
     */
    private static ApkInfo getApkInfo2(File file) throws IOException, XmlPullParserException {
        // apk信息的返回结果
        ApkInfo apkInfo=new ApkInfo();
        final AXmlResourceParser parser = new AXmlResourceParser();
        parser.open(getZipNodeCont(file,"AndroidManifest.xml"));
        // 遍历文件里的内容
        while (true) {
            final int type = parser.next();
            if (type == XmlPullParser.END_DOCUMENT) {
                break;
            }
            if (type==XmlPullParser.START_TAG){
                // 满足条件开始遍历内容提取需要的信息
                for (int i = 0; i != parser.getAttributeCount(); ++i) {
                    if ("package".equals(parser.getAttributeName(i))) {
                        apkInfo.setPackageName(ApkUtils.getAttributeValue(parser, i));
                    } else if ("versionCode".equals(parser.getAttributeName(i))) {
                        apkInfo.setVersionCode(Integer.valueOf(ApkUtils.getAttributeValue(parser, i)));
                    } else if ("versionName".equals(parser.getAttributeName(i))) {
                        apkInfo.setVersionName(ApkUtils.getAttributeValue(parser, i));
                    }
                }
            }
        }
        return apkInfo;
    }

    /**
     * 解码配置项值
     * @param parser
     * @param index
     * @return
     */
    private static String getAttributeValue(AXmlResourceParser parser, int index) {
        final int type = parser.getAttributeValueType(index);
        final int data = parser.getAttributeValueData(index);
        if (type == TypedValue.TYPE_STRING) {
            return parser.getAttributeValue(index);
        }
        if (type == TypedValue.TYPE_ATTRIBUTE) {
            return String.format("?%s%08X", ApkUtils.getPackage(data), data);
        }
        if (type == TypedValue.TYPE_REFERENCE) {
            return String.format("@%s%08X", ApkUtils.getPackage(data), data);
        }
        if (type == TypedValue.TYPE_FLOAT) {
            return String.valueOf(Float.intBitsToFloat(data));
        }
        if (type == TypedValue.TYPE_INT_HEX) {
            return String.format("0x%08X", data);
        }
        if (type == TypedValue.TYPE_INT_BOOLEAN) {
            return data != 0 ? "true" : "false";
        }
        if (type == TypedValue.TYPE_DIMENSION) {
            return Float.toString(ApkUtils.complexToFloat(data))
                    + ApkUtils.DIMENSION_UNITS[data & TypedValue.COMPLEX_UNIT_MASK];
        }
        if (type == TypedValue.TYPE_FRACTION) {
            return Float.toString(ApkUtils.complexToFloat(data))
                    + ApkUtils.FRACTION_UNITS[data & TypedValue.COMPLEX_UNIT_MASK];
        }
        if (type >= TypedValue.TYPE_FIRST_COLOR_INT && type <= TypedValue.TYPE_LAST_COLOR_INT) {
            return String.format("#%08X", data);
        }
        if (type >= TypedValue.TYPE_FIRST_INT && type <= TypedValue.TYPE_LAST_INT) {
            return String.valueOf(data);
        }
        return String.format("<0x%X, type 0x%02X>", data, type);
    }

    private static String getPackage(int id) {
        if (id >>> 24 == 1) {
            return "android:";
        }
        return "";
    }

    private static float complexToFloat(int complex) {
        return (complex & 0xFFFFFF00) * ApkUtils.RADIX_MULTS[complex >> 4 & 3];
    }

    /**
     * 读取zip压缩文件中指定条目的的内容
     * @param file 压缩文件对象
     * @param nodePathName 读取条目名称
     * @return 返回文件内容的inputStream
     */
    private static InputStream getZipNodeCont(File file, String nodePathName){
        //是否为目录中的文件
        boolean isDir=nodePathName.contains("/");
        // 获得一个解压文件对象
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(file);
            final Enumeration<? extends ZipEntry> enumeration =zipFile.entries();
            ZipEntry zipEntry = null;
            while (enumeration.hasMoreElements()){
                zipEntry=enumeration.nextElement();
                if (zipEntry.isDirectory()){
                    if (!isDir){continue;}
                }
                if (zipEntry.getName().equalsIgnoreCase(nodePathName)){
                    return zipFile.getInputStream(zipEntry);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


