// import DialogPanel from "../../dialog/DialogPanel";
// import { AC } from "../AndroidConnecter";
// import { prefabTestGameData } from "../data/GameData";
// import { EVT } from "../event/EventCenter";
// import { DialogType, GameEvents } from "../GameEnums";
// import { MapClass } from "../MapClass";

import { MapClass } from "../../list/MapClass";
import { preGameData } from "../prefabTestGameData";

export interface ZipData {
    picMap: MapClass<string>,
    audioMap: MapClass<string>,
    gifMap: MapClass<string>
}

export interface gifData {
    word: string,
    jsonMap: MapClass<string>,
    tex: cc.Texture2D
}
export default class ZipManager {
    /**json数据 */
    private static _jsonData = {}
    /**gif图数据Map */
    private static _gifDataMap: MapClass<string> = null;
    /**zip数据解析 */
    static fileTypeArr: Array<string> = ["jpg", "mp3", "gif", "png", "jpeg"];
    static imageTypeArr: Array<string> = ["jpg", "png", "jpeg"];

    static loadSubZip(zippath, cb) {
        this._jsonData = {};
        this._textureMap = {};
        preGameData.clearData();
        let t_newZip: JSZip = new JSZip(); // 因为将jszip导入为插件，所以可以全局直接访问
        // if (!this._newZip) this._newZip = new JSZip();
        t_newZip.loadAsync(zippath).then(zip => {
            let t_fileList = zip.files;

            let t_keys = Object.keys(t_fileList);
            this.loadSubZipAll(0, t_keys, zip, cb);
            // this._newZip.remove(zippath)
            t_newZip = null;
        });
    }

    private static loadSubZipAll(num: number, keys: Array<string>, zip: JSZip, cb: Function) {
        if (num >= keys.length) {
            preGameData.zipData.audioMap.sortKeys();
            cb && cb()
            return
        }
        let t_fileName = keys[num];
        // cc.log(filename);
        let t_strs = t_fileName.split("/");
        let t_wordName = t_strs[t_strs.length - 2];
        t_strs = t_strs[t_strs.length - 1].split(".");
        let t_word = t_strs[0];
        if (!t_wordName) {
            t_wordName = t_word;
        }
        // cc.log("wordName : " + wordName);
        let t_file = t_strs[1];
        if (t_strs.length < 2) {
            num++;
            this.loadSubZipAll(num, keys, zip, cb);
            return;
        }

        if (this.imageTypeArr.indexOf(t_strs[1]) != -1) {
            t_file = "gif";
        }

        switch (t_file) {
            case "jpg":
            case "png":
            case "jpeg":
                if (t_strs[1] == "db") {
                    num++;
                    this.loadSubZipAll(num, keys, zip, cb);
                } else {
                    this.loadSprite(zip, t_fileName, (sp) => {
                        preGameData.zipData.picMap.set(t_word, sp);
                        num++;
                        this.loadSubZipAll(num, keys, zip, cb);
                    })
                }
                break;
            case "mp3":
                if (t_strs[1] == "db") {
                    num++;
                    this.loadSubZipAll(num, keys, zip, cb);
                } else {
                    this.loadAudio(zip, t_fileName, (audioClip) => {
                        preGameData.zipData.audioMap.set(t_word, audioClip);
                        num++;
                        this.loadSubZipAll(num, keys, zip, cb);
                    })
                }
                break;
            case "gif":
                if (t_strs[1] == "db") {
                    num++;
                    this.loadSubZipAll(num, keys, zip, cb);
                } else {
                    let t_array: Array<any> = preGameData.zipData.gifMap.get(t_wordName);
                    if (!t_array) t_array = new Array<any>();
                    this.loadSprite(zip, t_fileName, (buffer) => {
                        t_array.push(buffer);
                        preGameData.zipData.gifMap.set(t_wordName, t_array);
                        num++;
                        this.loadSubZipAll(num, keys, zip, cb);
                    })
                }
                break;
            default:
                cc.log("error type ==>", t_fileName)
                num++;
                this.loadSubZipAll(num, keys, zip, cb);
                break;
        }
    }

    /**排序----解决的key值的错乱问题 */
    private static objOrder(obj: Array<any>) {
        let t_newKey = obj.sort(function (a, b) {
            return a - b;
        });
        return t_newKey;
    }
    /**读取图片 */
    static loadSprite(zip: JSZip, fileName: string, cb: Function, isGif: boolean = false) {
        zip.file(fileName).async("base64").then((data) => {
            if (!data) {
                cc.log("not fond image:", fileName);
                // AC.delZip(prefabTestGameData.getZipUrl());
                return;
            }
            let t_arr = fileName.split(".");
            if (t_arr.length < 1) {
                cc.log("res error:", fileName)
            }
            let t_suffix = t_arr[1]
            let t_strImg = "data:image/" + t_suffix + ";base64," + data;
            let t_img = new Image();
            t_img.src = t_strImg
            let t_texture = new cc.Texture2D();
            t_texture.initWithElement(t_img);
            let t_spriteFrame: cc.SpriteFrame = null;
            if (!isGif) {
                t_spriteFrame = new cc.SpriteFrame(t_texture);
                t_spriteFrame.addRef();
                cb && cb(t_spriteFrame);
            } else {
                cb && cb(t_texture);
            }
        }).catch((error) => {
            cc.log(`${fileName}图片加载失败`, error);
        })
    }

    /**读取音频 */
    static loadAudio(zip: JSZip, fileName: string, cb) {
        zip.file(fileName).async("arraybuffer").then((buffer) => {
            let t_arrayBuffer = buffer;
            let t_audioSupport = (cc.sys as any).__audioSupport;
            let t_context = t_audioSupport.context;
            t_context.decodeAudioData(t_arrayBuffer, (buffer) => {
                let t_audioClip: any = new cc.AudioClip();
                t_audioClip._nativeAsset = buffer;
                t_audioClip.duration = buffer.duration;
                cb && cb(t_audioClip);
            }, (error) => {
                cc.log(fileName, '解析失败-', error);
            });
        })
    }

    private static _textureMap = {};
    /**读取gif图---视听4.0不使用图集资源，使用散图 */
    private static loadGif(zip: JSZip, fileName: string, word: string, cb) {
        let t_frames = this._textureMap[fileName];
        if (t_frames) {
            cb && cb(t_frames)
            return
        }
        t_frames = [];
        let t_json = this._jsonData[word];
        this.loadSprite(zip, fileName, (texture: cc.Texture2D) => {
            for (let frameKey in t_json.frames) {
                let t_frame = t_json.frames[frameKey].frame;
                let t_tex = new cc.SpriteFrame(texture);
                let t_tmpRect = new cc.Rect(t_frame.x, t_frame.y, t_frame.w, t_frame.h);
                t_tex.setRect(t_tmpRect);
                t_tex.setRotated(t_frame.rotated)
                t_frames.push(t_tex);
            }
            let t_len = Object.keys(t_json.frames).length;

            let t_speed = 0;
            if (t_len < 10) {
                t_speed = 0.018 * t_len
            } else if (t_len >= 10 && t_len < 20) {
                t_speed = 0.015 * t_len
            } else {
                t_speed = 0.008 * t_len
            }

            cc.log("speed=>", word, t_speed, t_len, t_json);
            this._textureMap[word] = t_frames;
            cb && cb(t_frames, t_speed);
        }, true);
    }
}