package cn.com.ctop.common.module.utils;

import brut.androlib.res.decoder.AXmlResourceParser;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSString;
import com.dd.plist.PropertyListParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParser;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import static android.util.TypedValue.*;

/**
 *  Created by JQ.bi on 2020.9.9
 */
public class ParseInstallPackageUtil {

    private static final Logger log = LoggerFactory.getLogger(ParseInstallPackageUtil.class);

    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", "", "", "", "", "", ""};

    /**
     * 解析apk文件
     *
     * @param apkUrl apk的文件路径
     * @return
     */
    public static Map<String, String> parseAPK(String apkUrl) {
        Map<String, String> map = new HashMap();
        ZipFile zipFile;
        try {
            zipFile = new ZipFile(apkUrl);
            Enumeration<?> enumeration = zipFile.entries();
            ZipEntry zipEntry = null;
            while (enumeration.hasMoreElements()) {
                zipEntry = (ZipEntry) enumeration.nextElement();
                if (zipEntry.isDirectory()) {
                } else {
                    if ("androidmanifest.xml".equals(zipEntry.getName().toLowerCase())) {
                        AXmlResourceParser parser = new AXmlResourceParser();
                        parser.open(zipFile.getInputStream(zipEntry));
                        while (true) {
                            int type = parser.next();
                            if (type == XmlPullParser.END_DOCUMENT) {
                                break;
                            }
                            String name = parser.getName();
                            if (null != name && "manifest".equals(name.toLowerCase())) {
                                for (int i = 0; i != parser.getAttributeCount(); i++) {
                                    if ("versionName".equals(parser.getAttributeName(i))) {
                                        String versionName = getAttributeValue(parser, i);
                                        if (null == versionName) {
                                            versionName = "";
                                        }
                                        map.put("versionName", versionName);
                                    } else if ("package".equals(parser.getAttributeName(i))) {
                                        String packageName = getAttributeValue(parser, i);
                                        if (null == packageName) {
                                            packageName = "";
                                        }
                                        map.put("package", packageName);
                                    } else if ("versionCode".equals(parser.getAttributeName(i))) {
                                        String versionCode = getAttributeValue(parser, i);
                                        if (null == versionCode) {
                                            versionCode = "";
                                        }
                                        map.put("versionCode", versionCode);
                                    }
                                }
                                break;
                            }
                        }
                    }

                }
            }
            zipFile.close();
        } catch (Exception e) {
            log.info("APK解析异常！");
        }
        return map;
    }

    /**
     * 解析ipa文件
     *
     * @param ipaUrl ipa的文件路径
     * @return
     */
    public static Map<String, String> parseIpa(String ipaUrl) {
        Map<String, String> map = new HashMap();
        try {
            File file = new File(ipaUrl);
            InputStream is = new FileInputStream(file);
            ZipInputStream zipIns = new ZipInputStream(is);
            ZipEntry ze;
            InputStream infoIs = null;
            while ((ze = zipIns.getNextEntry()) != null) {
                if (!ze.isDirectory()) {
                    String name = ze.getName();
                    if (null != name && name.toLowerCase().contains(".app/info.plist")) {
                        ByteArrayOutputStream _copy = new ByteArrayOutputStream();
                        int chunk = 0;
                        byte[] data = new byte[1024];
                        while (-1 != (chunk = zipIns.read(data))) {
                            _copy.write(data, 0, chunk);
                        }
                        infoIs = new ByteArrayInputStream(_copy.toByteArray());
                        break;
                    }
                }
            }

            NSDictionary rootDict = (NSDictionary) PropertyListParser.parse(infoIs);

            // 应用包名
            NSString parameters = (NSString) rootDict.get("CFBundleIdentifier");
            map.put("package", parameters.toString());
            // 应用版本名
            parameters = (NSString) rootDict.objectForKey("CFBundleShortVersionString");
            map.put("versionName", parameters.toString());
            // 应用版本号
            parameters = (NSString) rootDict.get("CFBundleVersion");
            map.put("versionCode", parameters.toString());

            infoIs.close();
            is.close();
            zipIns.close();

        } catch (Exception e) {
            log.info("ipa包解析异常！");
        }
        return map;
    }


    private static String getAttributeValue(AXmlResourceParser parser, int index) {

        int type = parser.getAttributeValueType(index);
        int data = parser.getAttributeValueData(index);
        if (type == TYPE_STRING) {
            return parser.getAttributeValue(index);
        }
        if (type == TYPE_ATTRIBUTE) {
            return String.format("?%s%08X", getPackage(data), data);
        }
        if (type == TYPE_REFERENCE) {
            return String.format("@%s%08X", getPackage(data), data);
        }
        if (type == TYPE_FLOAT) {
            return String.valueOf(Float.intBitsToFloat(data));
        }
        if (type == TYPE_INT_HEX) {
            return String.format("0x%08X", data);
        }
        if (type == TYPE_INT_BOOLEAN) {
            return data != 0 ? "true" : "false";
        }
        if (type == TYPE_DIMENSION) {
            return Float.toString(complexToFloat(data)) + DIMENSION_UNITS[data & COMPLEX_UNIT_MASK];
        }
        if (type == TYPE_FRACTION) {
            return Float.toString(complexToFloat(data)) + FRACTION_UNITS[data & COMPLEX_UNIT_MASK];
        }
        if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) {
            return String.format("#%08X", data);
        }
        if (type >= TYPE_FIRST_INT && type <= 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 (float) (complex & 0xFFFFFF00) * RADIX_MULTS[(complex >> 4) & 3];
    }

    public static void printMap(Map<String, String> map) {
        for (String key : map.keySet()) {
            log.info(key + ":" + map.get(key));
        }

    }
}
