package com.saki.plugin.dictionary;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import com.saki.QVMProtect;
import com.saki.tools.FileUtil;

import com.file.zip.ZipEntry;
import com.file.zip.ZipFile;

import android.content.Context;
@QVMProtect
public class DicFactroy {

    public static void Dic2Dic(Context c, DicHandler h, Dictionary old,
                               Dictionary now, boolean deleteOld) {
        HashMap<String, String[]> map = now.getDictionary();
        Iterator<String> it = map.keySet().iterator();
        int i = 0;
        while (it.hasNext()) {
            i++;
            String key = it.next();
            if (deleteOld) {
                old.getDictionary().put(key, map.get(key));
                h.sendInfo(i, true);
            } else {
                h.sendInfo(i, old.addValue(key, map.get(key)));
            }
        }
        try {
            old.saveDictionary2File(Dictionary.dicFile, getCharset(c));
        } catch (IOException e) {
            h.sendInfo("合并完成！保存失败!错误信息:" + e.toString());
        }
        h.sendEnd();
    }

    private static String getCharset(Context c) {
        return c.getSharedPreferences(DictionaryView.CONFIGNAME,
                Context.MODE_PRIVATE)
                .getString(DictionaryView.CHARSET, "UTF-8");
    }

    public static void importDic(Context c, final DicHandler h,
                                 final String path) {
        File f = new File(FileUtil.BASE_PATH + "DictionaryV8/dic.txt");
        h.sendInfo("正在删除dic:" + f.delete());
        importDic(c, h, path, true);
    }

    public static void importDic(final Context c, final DicHandler h,
                                 final String path, final boolean deleteOld) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File f = new File(path);
                if (!f.exists()) {
                    h.sendInfo("需要合并的词库文件不存在:" + path);
                    return;
                }
                h.sendInfo("正在加载旧dic....");
                Dictionary dic = new Dictionary();
                try {
                    dic.loadDictionary2Memory(getCharset(c));
                } catch (IOException e) {
                    String err = e.toString();
                    for (StackTraceElement t : e.getStackTrace()) {
                        err += "\n" + t.toString();
                    }
                    h.sendInfo("加载失败!错误信息:" + err);
                }
                h.sendInfo("加载完成:共加载" + dic.getLength() + "条词库!");
                if (f.getName().endsWith(".txt")) {
                    h.sendInfo("开始读取新词库...");
                    Dictionary ndic = new Dictionary();
                    try {
                        ndic.loadDictionary2Memory(f, getCharset(c));
                    } catch (IOException e) {
                        String err = e.toString();
                        for (StackTraceElement t : e.getStackTrace()) {
                            err += "\n" + t.toString();
                        }
                        h.sendInfo("加载失败!错误信息:" + err);
                        return;
                    }
                    h.sendInfo("加载成功:共加载" + ndic.getLength()
                            + "条词库!\n——————开始合并——————");
                    DicFactroy.Dic2Dic(c, h, dic, ndic, deleteOld);
                } else {
                    h.sendInfo("正在解压...");
                    try {
                        ZipFile zip = new ZipFile(f, "GBK");
                        Enumeration<ZipEntry> e = zip.getEntries();
                        while (e.hasMoreElements()) {
                            ZipEntry entry = e.nextElement();
                            if (entry.getName().contains("SakiDictionary")) {
                                if (entry.isDirectory()) {
                                    File path = new File(FileUtil.BASE_PATH
                                            + entry.getName());
                                    if (!path.exists()) {
                                        h.sendInfo("创建目录:"
                                                + path.getAbsolutePath()
                                                + (path.mkdirs() ? "[成功]"
                                                : "[失败]"));
                                    }
                                } else {
                                    if (entry.getName().contains("/dic.txt")) {
                                        h.sendInfo("发现压缩dic文件:"
                                                + entry.getName() + "\n开始载入...");
                                        InputStream is = zip
                                                .getInputStream(entry);
                                        Dictionary ndic = new Dictionary();
                                        ndic.loadDictionary2Memory(is,
                                                getCharset(c));
                                        h.sendInfo("载入新dic:" + ndic.getLength()
                                                + "条,正在合并...");
                                        DicFactroy.Dic2Dic(c, h, dic, ndic,
                                                deleteOld);
                                    } else {
                                        h.sendInfo("正在解压文件:" + entry.getName());
                                        File mf = new File(FileUtil.BASE_PATH
                                                + entry.getName());
                                        if (!mf.exists()) {
                                            h.sendInfo("创建文件:"
                                                    + (mf.createNewFile() ? "[成功]"
                                                    : "[失败]"));
                                        }
                                        FileOutputStream out = new FileOutputStream(
                                                mf);
                                        InputStream is = zip
                                                .getInputStream(entry);
                                        int i = -1;
                                        while ((i = is.read()) != -1) {
                                            out.write(i);
                                        }
                                        out.flush();
                                        out.close();
                                        is.close();
                                        h.sendInfo("解压完成!");
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        String err = e.toString();
                        for (StackTraceElement t : e.getStackTrace()) {
                            err += "\n" + t.toString();
                        }
                        h.sendInfo("解压失败!错误信息:" + err);
                        return;
                    }
                }
            }
        }).start();
    }
}
