package com.house365.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

/**
 * APK解压/压缩工具
 * @author FanLei
 * @version v1.0
 * 2015-12-21 上午11:03:36
 */
public class ApkUtil {
    private static final int BUFFER = 1024;
    private static final String BASE_DIR = "";

    /**符号"/"用来作为目录标识判断符*/
    private static final String PATH = "/";

    /**签名目录*/
    private static final String SIGN_PATH_NAME = "META-INF";
    /**解压源文件目录*/
    private static final String SOURCE_PATH_NAME = "\\source\\";
    /**打包目录*/
    private static final String TARGET_PATH_NAME = "\\target\\";

    /**
    * 解压缩zip文件
    * @param fileName 要解压的文件名 包含路径 如："c:\\test.zip"
    * @param filePath 解压后存放文件的路径 如："c:\\temp"
    * @throws Exception
    */
    @SuppressWarnings("rawtypes")
    public static void unZip(String fileName, String filePath) throws Exception {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.getEntries();

        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            byte[] buf = new byte[BUFFER];
            int len = 0;
            while ((len = bis.read(buf, 0, BUFFER)) != -1) {
                fos.write(buf, 0, len);
            }
            bos.flush();
            bos.close();
            bis.close();
        }
        zipFile.close();
    }

    /**
     * 压缩文件
     *
     * @param srcFile
     * @param destPath
     * @throws Exception
     */
    public static void compress(String srcFile, String destPath) throws Exception {
        compress(new File(srcFile), new File(destPath));
    }

    /**
     * 压缩
     *
     * @param srcFile
     *            源路径
     * @param destPath
     *            目标路径
     * @throws Exception
     */
    public static void compress(File srcFile, File destFile) throws Exception {
        // 对输出文件做CRC32校验
        CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(destFile), new CRC32());

        ZipOutputStream zos = new ZipOutputStream(cos);
        compress(srcFile, zos, BASE_DIR);

        zos.flush();
        zos.close();
    }

    /**
     * 压缩
     *
     * @param srcFile
     *            源路径
     * @param zos
     *            ZipOutputStream
     * @param basePath
     *            压缩包内相对路径
     * @throws Exception
     */
    private static void compress(File srcFile, ZipOutputStream zos, String basePath) throws Exception {
        if (srcFile.isDirectory()) {
            compressDir(srcFile, zos, basePath);
        } else {
            compressFile(srcFile, zos, basePath);
        }
    }

    /**
     * 压缩目录
     *
     * @param dir
     * @param zos
     * @param basePath
     * @throws Exception
     */
    private static void compressDir(File dir, ZipOutputStream zos, String basePath) throws Exception {
        File[] files = dir.listFiles();
        // 构建空目录
        if (files.length < 1) {
            ZipEntry entry = new ZipEntry(basePath + dir.getName() + PATH);

            zos.putNextEntry(entry);
            zos.closeEntry();
        }

        String dirName = "";
        String path = "";
        for (File file : files) {
            // 当父文件包名为空时，则不把包名添加至路径中（主要是解决压缩时会把父目录文件也打包进去）
            if (basePath != null && !"".equals(basePath)) {
                dirName = dir.getName();
            }
            path = basePath + dirName + PATH;
            // 递归压缩
            compress(file, zos, path);
        }
    }

    /**
     * 文件压缩
     *
     * @param file
     *            待压缩文件
     * @param zos
     *            ZipOutputStream
     * @param dir
     *            压缩文件中的当前路径
     * @throws Exception
     */
    private static void compressFile(File file, ZipOutputStream zos, String dir) throws Exception {
        /**
         * 压缩包内文件名定义
         *
         * <pre>
         * 如果有多级目录，那么这里就需要给出包含目录的文件名
         * 如果用WinRAR打开压缩包，中文名将显示为乱码
         * </pre>
         */
        if ("/".equals(dir))
            dir = "";
        else if (dir.startsWith("/")) dir = dir.substring(1, dir.length());

        ZipEntry entry = new ZipEntry(dir + file.getName());
        zos.putNextEntry(entry);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = bis.read(data, 0, BUFFER)) != -1) {
            zos.write(data, 0, count);
        }
        bis.close();

        zos.closeEntry();
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public static void startBuild(String srcPath, String channel) throws Exception {
        StringBuffer buffer = new StringBuffer();

        File srcFile = new File(srcPath);
        String parentPath = srcFile.getParent();    // 源文件目录
        String fileName = srcFile.getName();        // 源文件名称
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        String offixName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        // 解压源文件保存路径
        String sourcePath = buffer.append(parentPath).append(SOURCE_PATH_NAME).append(prefixName)
                .append("\\").toString();

        // 解压
        unZip(srcPath, sourcePath);

        // 创建空渠道文件
        File channelFile = new File(sourcePath + SIGN_PATH_NAME + File.separator + channel);
        if (!channelFile.exists()) {
            channelFile.createNewFile();
        }

        // 重新压缩APK后的目标路径
        String targetPath = parentPath + TARGET_PATH_NAME;
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            targetFile.mkdir();
        }

        // 压缩
        compress(parentPath + SOURCE_PATH_NAME + prefixName, targetPath + channel + offixName);

        // 删除解压目录
        deleteDir(new File(sourcePath));
    }

    public static void main(String[] args) throws Exception {
        StringBuffer buffer = new StringBuffer();

        String srcPath = "E:\\Work_Space\\apk_redist\\main-test\\ApkUtil\\taofang_xzy.apk";
        String content = "365_taofang_机锋";

        File srcFile = new File(srcPath);
        String parentPath = srcFile.getParent();    // 源文件目录
        String fileName = srcFile.getName();        // 源文件名称
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        String offixName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        // 解压源文件保存路径
        String sourcePath = buffer.append(parentPath).append(SOURCE_PATH_NAME).append(prefixName)
                .append("\\").toString();

        // 解压
        //unZip(srcPath, sourcePath);

        // 创建空渠道文件
        File channelFile = new File(sourcePath + SIGN_PATH_NAME + File.separator + content);
        if (!channelFile.exists()) {
            channelFile.createNewFile();
        }

        // 重新压缩APK后的目标路径
        String targetPath = parentPath + TARGET_PATH_NAME;
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            targetFile.mkdir();
        }

        // 压缩
        compress(parentPath + SOURCE_PATH_NAME + prefixName, targetPath + content + offixName);

        // 删除解压目录
        deleteDir(new File(sourcePath));
    }
}
