package com.saki.plugin.dictionary;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import com.saki.QVMProtect;
import com.saki.log.SQLog;
import com.saki.qq.global.Global;
import com.saki.qq.global.TroopManager;
import com.saki.service.NewService;

import com.setqq.script.Msg;
import com.setqq.script.sdk.ScriptSend;
import com.setqq.script.sdk.SendInterface;
import com.setqq.script.sdk.IScript;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
@QVMProtect
public class AppDictionaryV8 implements IScript {
    private NewService context = null;
    private SendInterface api;
    public Set<String> blackList;
    public DictionaryV8 dictionary;

    // private String tag="dic";
    private String getCharset() {
        return context.getSharedPreferences(DictionaryView.CONFIGNAME,
                Context.MODE_PRIVATE)
                .getString(DictionaryView.CHARSET, "UTF-8");
    }

    private long[] getIDlist(ArrayList<String> arr) {
        if (arr == null || arr.size() == 0)
            return new long[0];
        long[] id = new long[arr.size()];
        for (int i = 0; i < id.length; i++) {
            String at = arr.get(i);
            id[i] = Long.parseLong(at.substring(0, at.indexOf('@')));
        }
        return id;
    }

    private String getMaster() {
        return context.getSharedPreferences(DictionaryView.CONFIGNAME,
                Context.MODE_PRIVATE).getString(DictionaryView.MASTER, "0");
    }

    private boolean getReplay(String key) {
        return context.getSharedPreferences(DictionaryView.CONFIGNAME,
                Context.MODE_PRIVATE).getBoolean(key, false);
    }

    @SuppressLint("NewApi")
    private boolean inBlackList(long uin) {
        if (blackList == null) {
            SharedPreferences sp = context.getSharedPreferences(
                    DictionaryView.CONFIGNAME, Context.MODE_PRIVATE);
            blackList = new HashSet<String>();
            sp.getStringSet(DictionaryView.BLACKLIST, blackList);
        }
        return blackList.contains(String.valueOf(uin));
    }

    @Override
    public void onLoad(NewService context) {
        this.context = context;
        dictionary = new DictionaryV8();
        dictionary.checkDictionaryFile();
        this.api = new ScriptSend(context);
    }

    @Override
    public void onMessageHandler(Msg msg) {
        if (msg == null)
            return;
        try {
            // long time=System.currentTimeMillis();
            String m = msg.getTextMsg();
            // Log.i(tag, "dic开始处理消:"+m);
            if (context == null || m.equals("") || msg.uin == Global.qq)
                return;
            // 群是否打勾
            if (msg.type == Msg.TYPE_GROUP_MSG
                    && !TroopManager.getInstance().isOPen(msg.groupid))
                return;
            // 是否允许群回复
            if (msg.type == Msg.TYPE_GROUP_MSG
                    && !true)
                return;
            // 是否允许好友回复
            if (msg.type == Msg.TYPE_BUDDY_MSG
                    && !getReplay(DictionaryView.BUDDY_REPLY))
                return;
            // 是否允许讨论组回复
            if (msg.type == Msg.TYPE_DIS_MSG
                    && !getReplay(DictionaryView.DIS_REPLY))
                return;
            // 是否处于黑名单
            if (inBlackList(msg.groupid) || inBlackList(msg.uin))
                return;
            String s[] = null;
            // Log.i(tag, "是否打开缓存:"+dictionary.isCacheMode());
            if (dictionary.isCacheMode()) {
                s = dictionary.findValueOfCache(m);
                // Log.i(tag,
                // "已获取缓存结果共耗时:"+(System.currentTimeMillis()-time)+"ms");
            }
            if (s == null) {
                // Log.i(tag, "正在查找关键字...");
                BufferedReader read = dictionary.findKey(m, msg.type,
                        getCharset());
                // Log.i(tag,
                // "已获取查找结果共耗时:"+(System.currentTimeMillis()-time)+"ms");
                if (read != null) {
                    s = dictionary.findValue(read, true);
                    // Log.i(tag,
                    // "已获取词条结果共耗时:"+(System.currentTimeMillis()-time)+"ms");
                }
            }
            if (s == null || s.length <= 0)
                return;
            // time=System.currentTimeMillis();
            // Log.i(tag, "正在解析词库代码...");
            String resault = new TempPseudoCode(context, msg, getMaster(),m,getIDlist(msg.getMsg("at"))).executeCode(s);
            // Log.i(tag, "执行完成，耗时:"+(System.currentTimeMillis()-time)+"ms");
            if (!resault.equals("")) {
                if (resault.matches("(?i)(?s)card:[0-9]+.*")) {
                    String xml = resault.replaceAll("(?i)(?s)card:[0-9]+(.*)",
                            "$1");
                    msg.clearMsg();
                    msg.addMsg("xml", xml);
                    api.send(msg);
                    // context.startService(CmdIntent.getMsgSendIntent(context,
                    // msg.groupid,msg.uin, null,xml, null,null));
                } else if (resault.matches("(?i)(?s)json:.*")) {
                    String json = resault.substring(5);
                    msg.clearMsg();
                    msg.addMsg("json", json);
                    api.send(msg);
                } else {
                    resault = resault.replaceAll("\\\\r", "\r");
                    msg.clearMsg();
                    String s2[] = resault.split("±");
                    for (String s3 : s2) {
                        if (s3.indexOf("img") == 0) {
                            msg.addMsg("img", s3.substring(4));
                        } else {
                            if (!s3.equals(""))
                                msg.addMsg("msg", s3);
                        }
                    }
                    api.send(msg);
                }
            }
        } catch (Exception e) {
            StringWriter w;
            PrintWriter sw = new PrintWriter(w = new StringWriter());
            e.printStackTrace(sw);
            SQLog.e("高级词库发生异常:" + e.toString() + "\r\n" + w.toString());
        }
    }

    @Override
    public String onAction(String value) {
        return value;
    }

    @Override
    public void delete() {
    }

    @Override
    public void destroy() {
    }

    @Override
    public String getViewUrl() {
        return null;
    }
    @Override
    public void runFunction(String funName,String param){};
}
