package com.android.common.utils;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipFile;

/**
 * zip文件解压缩任务，支持zip内多级目录结构
 *
 * Created By chengzhenyu
 */
public class FileUnzipTask {

    private String unZipDir;
    private String zipFilePath;
    private AsyncTask unzipTask;
    private FileUnzipListener listener;

    private boolean isCancelled;

    private static final int BUF_SIZE = 2048;

    private static final String TAG = "FileUnzipTask";

    public interface FileUnzipListener {
        void onUnzipSuccess(String zipFilePath, String unZipDir);
        void onUnzipError(int errorCode, String zipFilePath, String unZipDir);
    }

    public FileUnzipTask(String zipFilePath, String unZipDir, FileUnzipListener listener) {
        this.listener = listener;
        this.unZipDir = unZipDir;
        this.zipFilePath = zipFilePath;
    }

    public void startUnZip() {
        isCancelled = false;

        unzipTask = new AsyncTask<Object, Integer, Boolean>() {

            @Override
            protected Boolean doInBackground(Object... params) {
                try {
                    File desDir = new File(unZipDir);
                    if (!desDir.exists()) {
                        desDir.mkdirs();
                    }
                    ZipFile zf = new ZipFile(zipFilePath);
                    for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                        if(isCancelled){
                            break;
                        }
                        java.util.zip.ZipEntry entry = ((java.util.zip.ZipEntry)entries.nextElement());
                        InputStream in = zf.getInputStream(entry);
                        String str = unZipDir + File.separator + entry.getName();
                        str = new String(str.getBytes("8859_1"), "GB2312");
                        File desFile = new File(str);
                        if (!desFile.exists()) {
                            File fileParentDir = desFile.getParentFile();
                            if (!fileParentDir.exists()) {
                                fileParentDir.mkdirs();
                            }
                            if(entry.isDirectory()){
                                desFile.mkdirs();
                                continue;
                            }else{
                                desFile.createNewFile();
                            }
                        }
                        OutputStream out = new FileOutputStream(desFile);
                        byte buffer[] = new byte[BUF_SIZE];
                        int realLength;
                        while ((realLength = in.read(buffer)) > 0) {
                            out.write(buffer, 0, realLength);
                        }
                        in.close();
                        out.close();
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                LogHelper.d(TAG, "unzip task onPostExecute result=" + result);
                if (result) {
                    listener.onUnzipSuccess(zipFilePath, unZipDir);
                } else {
                    listener.onUnzipError(-1, zipFilePath, unZipDir);
                }
            }
        };
        unzipTask.execute();
    }

    public void cancelUnzip() {
        if (unzipTask != null) {
            isCancelled = true;
            unzipTask.cancel(true);
        }
    }
}
