package net.northking.cctp.scriptcase.tools;

import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSString;
import com.dd.plist.PropertyListParser;
import net.northking.cctp.scriptcase.enums.PlatformType;
import net.northking.cctp.scriptcase.tools.iosPng.NorthKingIpaPngFix;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class IpaUtil {
    private static Logger logger= LoggerFactory.getLogger(IpaUtil.class);

    /**
     * 通过IPA文件获取Info信息
     */
    public static Map<String, Object> getVersionInfo(File ipaFile) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        InputStream infoIs = null;
        ZipFile zipFile = new ZipFile(ipaFile, "utf-8");
        Enumeration<ZipEntry> entries = zipFile.getEntries();
        NSDictionary rootDict = null;
        String icon = null;
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                logger.info(name);
                if (null != name && name.toLowerCase().contains(".app/info.plist")&&name.split("/").length==3) {
                    ByteArrayOutputStream _copy = new ByteArrayOutputStream();
                    int chunk = 0;
                    byte[] data = new byte[1024];
                    infoIs = zipFile.getInputStream(zipEntry);
                    while (-1 != (chunk = infoIs.read(data))) {
                        _copy.write(data, 0, chunk);
                    }
                    infoIs = new ByteArrayInputStream(_copy.toByteArray());
                    rootDict = (NSDictionary) PropertyListParser.parse(infoIs);

                    //我们可以根据info.plist结构获取任意我们需要的东西
                    //比如下面我获取图标名称，图标的目录结构请下面图片
                    //获取图标名称
                    NSDictionary iconDict = (NSDictionary) rootDict.get("CFBundleIcons");
                    while (null != iconDict) {
                        if (iconDict.containsKey("CFBundlePrimaryIcon")) {
                            NSDictionary CFBundlePrimaryIcon = (NSDictionary) iconDict.get("CFBundlePrimaryIcon");
                            if (CFBundlePrimaryIcon.containsKey("CFBundleIconFiles")) {
                                NSArray CFBundleIconFiles = (NSArray) CFBundlePrimaryIcon.get("CFBundleIconFiles");
                                icon = CFBundleIconFiles.getArray()[0].toString();
                                if (icon.contains(".png")) {
                                    icon = icon.replace(".png", "");
                                }
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
        String data = null;
        Enumeration<ZipEntry> entries2 = zipFile.getEntries();
        while (entries2.hasMoreElements()) {
            ZipEntry zipEntry = entries2.nextElement();
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                if (!StringUtils.isEmpty(icon) && name.contains(icon.trim())) {
                    infoIs = zipFile.getInputStream(zipEntry);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    int i = 0;
                    byte[] bytes = new byte[1024];
                    while ((i = infoIs.read(bytes))!=-1){
                        byteArrayOutputStream.write(bytes,0,i);
                    }
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    NorthKingIpaPngFix fix = new NorthKingIpaPngFix(byteArray);
                    byte[] convert = fix.convert("png");
                    byteArrayOutputStream.flush();
                    byteArrayOutputStream.close();
                    logger.info("读取的文件名字：{}",name);
                    logger.info("读取的流是否为空：{}",byteArray == null);
                    logger.info("转换后的流是否为空：{}",convert==null);
                    byte[] baseByte = Base64.getEncoder().encode(convert);
                    String base64 = new String(baseByte, StandardCharsets.UTF_8);
                    data = base64;
                    break;
                }
            }
        }
        // 应用包名
        NSString parameters = (NSString) rootDict.get("CFBundleIdentifier");
        map.put("packageName", parameters.toString());

        // 应用名称
        parameters = (NSString) rootDict.objectForKey("CFBundleName");
        map.put("appName", parameters.toString());


        // 应用版本名
        parameters = (NSString) rootDict.objectForKey("CFBundleShortVersionString");
        map.put("buildVersion", parameters.toString());
        map.put("platform", PlatformType.getCode("ios"));



        parameters = (NSString) rootDict.objectForKey("CFBundleInfoDictionaryVersion");
        if (parameters!=null){
            float f=Float.valueOf(parameters.toString());
            int i=(int)f;
            map.put("versionCode",i);
        }else{
            map.put("versionCode",6);
        }
        if (data!=null&&data.length()>0){
            map.put("appIcon", data);
        }
        return map;
    }
}
