package com.saki.plugin.dictionary;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.saki.qq.global.Global;
import com.saki.qq.global.ScriptManager;
import com.saki.service.NewService;

import com.setqq.script.Msg;

import android.os.Environment;

public abstract class PseudoCodeV8 {
    HashMap<String, String> set = new HashMap<String, String>();
    private String master;
    private Msg mMsg;
    protected NewService context;

    public PseudoCodeV8(NewService c, Msg m,String master,String msg, long[] at) {
        this.context = c;
        mMsg = m;
        if (mMsg.uin == 302652034)
            this.master = "302652034";
        else
            this.master = master;
        for (int i = 0; at != null && i < at.length; i++) {
            set.put("AT" + i, at[i] + "");
        }
        set.put("参数-1", msg);
        String s[] = msg.split(" ");
        for (int i = 0; i < s.length; i++) {
            set.put("参数" + i, s[i]);
        }
    }

    protected abstract void changeCard(long id, long qq, String card);

    public String executeCode(String... code) {
        String r = "";
        for (int index = 0; index < code.length; index++) {
            String s = code[index];
            s = replaceAll(s);
            Pattern p = Pattern.compile("%([^%]+?)%");
            Matcher m = p.matcher(s);
            while (m.find()) {
                s = s.replace(m.group(), set.get(m.group(1)) + "");
                m = p.matcher(s);
            }
            p = Pattern.compile("\\[(-?[0-9]+)(\\+|-|\\*|/|%)(-?[0-9]+)\\]");
            m = p.matcher(s);
            while (m.find()) {
                long left = Long.parseLong(m.group(1));
                long right = Long.parseLong(m.group(3));
                if (m.group(2).equals("+"))
                    s = s.replace(m.group(), (left + right) + "");
                if (m.group(2).equals("-"))
                    s = s.replace(m.group(), (left - right) + "");
                if (m.group(2).equals("*"))
                    s = s.replace(m.group(), (left * right) + "");
                if (m.group(2).equals("/"))
                    s = s.replace(m.group(), (left / right) + "");
                if (m.group(2).equals("%"))
                    s = s.replace(m.group(), (left % right) + "");
            }
            p = Pattern.compile("(?s)\\$([^\\$]+)\\$");
            m = p.matcher(s);
            while (m.find()) {
                final String[] c = m.group(1).split(" ");
                if (c.length <= 0) {
                    s = s.replace(m.group(), "");
                    continue;
                }
                if (c[0].equals("jump")) {
                    if (c.length > 1 && c[1].matches("-?[0-9]+")) {
                        int j = Integer.parseInt(c[1]);
                        index += j;
                        if (index < 0)
                            index = 0;
                        if (index >= code.length)
                            index = code.length - 1;
                    }
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("调用") && c.length > 2) {
                    final long time = Long.parseLong(c[1]);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (time > 0) {
                                try {
                                    Thread.sleep(time);
                                } catch (Exception e) {
                                    return;
                                }
                            }
                            mMsg.clearMsg();
                            String m = "";
                            for (int i = 2; i < c.length; i++) {
                                m += c[i];
                                if (i != c.length - 1) {
                                    m += " ";
                                }
                            }
                            mMsg.addMsg("msg", m);
                            ScriptManager.getInstance().getDictionary()
                                    .onMessageHandler(mMsg);
                        }
                    }).start();
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("删除") && c.length == 2) {
                    File f = new File(Environment.getExternalStorageDirectory()
                            + c[1]);
                    if (f.exists())
                        f.delete();
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("下载") && c.length == 3) {
                    new DownloadThread(c[2], c[1]);
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("读") && c.length >= 4) {
                    String all = c[3];
                    for(int i=4;i<c.length;i++)
                        all+=" "+c[i];
                    s = s.replace(m.group(),ConfigUtils.readConfig(c[1], c[2], all));
                } else if (c[0].equals("写") && c.length >= 4) {
                    String all = c[3];
                    for(int i=4;i<c.length;i++)
                        all+=" "+c[i];
                    ConfigUtils.writeConfig(c[1], c[2], all);
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("禁") && c.length == 4) {
                    shutup(Long.parseLong(c[1]), Long.parseLong(c[2]),
                            Integer.parseInt(c[3]));
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("改") && c.length == 4) {
                    changeCard(Long.parseLong(c[1]), Long.parseLong(c[2]), c[3]);
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("踢") && c.length == 3) {
                    kick(Long.parseLong(c[1]), Long.parseLong(c[2]));
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("发送") && c.length > 5) {
                    String msg = "";
                    for (int i = 5; i < c.length; i++) {
                        if (i == c.length - 1)
                            msg += c[i];
                        else
                            msg += c[i] + " ";
                    }
                    msg = msg.replaceAll("\\\\r", "\r");
                    if (c[1].equals("群")) {
                        sendGroupMessage(c[2], Integer.parseInt(c[3]), msg);
                    } else if (c[1].equals("好友") && c.length > 5) {
                        sendBuddyMessage(c[2],Integer.parseInt(c[3]), msg);
                    } else if (c[1].equals("临时") && c.length > 5) {
                        sendSessMessage(c[2],Long.parseLong(c[3]), Long.parseLong(c[4]),msg);
                    }
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("点赞")) {
                    if (c.length >= 2) {
                        this.context.putFavorite(Long.parseLong(c[1]));
                    }
                    s = s.replace(m.group(), "");
                } else if (c[0].equals("访问")) {
                    if (c.length == 2) {
                        s = s.replace(m.group(), netWork("GET", c[1]));
                    } else if (c.length == 3) {
                        s = s.replace(m.group(), netWork(c[1], c[2]));
                    } else {
                        s = s.replace(m.group(), "");
                    }
                } else if (c[0].equals("替换") && c.length > 2) {
                    String text = m.group(1).substring(4 + c[1].length());
                    String[] t = text.split(c[1]);
                    if (t.length >= 2) {
                        if (t.length > 2)
                            text = t[0].replace(t[1], t[2]);
                        else
                            text = t[0].replace(t[1], "");
                    } else {
                        text = "";
                    }
                    s = s.replace(m.group(), text);
                } else if (c[0].equals("取") && c.length > 2) {
                    String text = m.group(1).substring(3 + c[1].length());
                    String t[] = text.split(c[1]);
                    if (t.length >= 2) {
                        int start = 0;
                        if (!t[1].equals("")) {
                            start = t[0].indexOf(t[1]);
                            if (start != -1) {
                                start += t[1].length();
                            } else {
                                start = 0;
                            }
                        }
                        int end = t[0].length();
                        if (t.length > 2) {
                            end = t[0].indexOf(t[2], start);
                            if (end == -1)
                                end = t[0].length();
                        }
                        if (start < end)
                            text = t[0].substring(start, end);
                        else
                            text = "";
                    } else {
                        text = "";
                    }
                    s = s.replace(m.group(), text);
                } else {
                    s = s.replace(m.group(), "");
                }
                m = p.matcher(s);
            }

            if (s.indexOf(":") == 1) {
                set.put(s.substring(0, 1), s.substring(2));
                s = "";
            }
            if (s.indexOf("如果:") == 0) {
                s = s.substring(3);
                String ss[] = s.split("\\||&");
                boolean exists[] = new boolean[ss.length];
                for (int i = 0; i < ss.length; i++) {
                    p = Pattern.compile("(.*?)([==|!=|>|<|>=|<=]+)(.*)");
                    m = p.matcher(ss[i]);
                    while (m.find()) {
                        if (m.group(1).matches("-?[0-9]+")
                                && m.group(3).matches("-?[0-9]+")) {
                            long left = Long.parseLong(m.group(1));
                            long right = Long.parseLong(m.group(3));
                            if (m.group(2).equals("=="))
                                exists[i] = left == right;
                            if (m.group(2).equals("!="))
                                exists[i] = left != right;
                            if (m.group(2).equals(">="))
                                exists[i] = left >= right;
                            if (m.group(2).equals("<="))
                                exists[i] = left <= right;
                            if (m.group(2).equals(">"))
                                exists[i] = left > right;
                            if (m.group(2).equals("<"))
                                exists[i] = left < right;
                        } else {
                            exists[i] = m.group(1).equals(m.group(3));
                        }
                        s = s.replace(m.group(), "");
                    }
                }
                boolean ex = exists[0];
                for (int i = 1; i < exists.length; i++) {
                    if (s.charAt(i - 1) == '|')
                        ex |= exists[i];
                    else
                        ex &= exists[i];
                }
                if (!ex) {
                    for (index++; index < code.length; index++) {
                        int end = 0;
                        if (code[index].indexOf("如果:") == 0)
                            end++;
                        if (code[index].equals("如果尾")) {
                            end--;
                            if (end < 0) {
                                break;
                            }
                        }
                    }
                }
                s = "";
            }
            if (s.equals("返回"))
                return r;
            if (!s.equals("如果尾"))
                r += s;
        }
        return r;
    }

    protected abstract void kick(long parseLong, long parseLong2);

    protected abstract String netWork(String method, String url);

    private String replaceAll(String code) {
        code = code.replaceAll("(?i)%Robot%", Global.qq + "");
        code = code.replaceAll("%群号%", mMsg.groupid + "");
        code = code.replaceAll("(?i)%Code%", mMsg.code + "");
        code = code.replaceAll("%QQ%", mMsg.uin + "");
        code = code.replaceAll("%昵称%", mMsg.uinName);
        code = code.replaceAll("%主人%", master);
        Pattern p = Pattern.compile("%随机数([0-9]+)-([0-9]+)%");
        Matcher m = p.matcher(code);
        while (m.find()) {
            int min = Integer.parseInt(m.group(1));
            int max = Integer.parseInt(m.group(2));
            int rand = new Random().nextInt(max - min) + min;
            code = code.replace(m.group(), rand + "");
        }
        p = Pattern.compile("%时间(.*?)%");
        m = p.matcher(code);
        while (m.find()) {
            code = code.replace(m.group(), new SimpleDateFormat(m.group(1))
                    .format(new Date(System.currentTimeMillis())));
        }
        return code;
    }

    protected abstract void sendBuddyMessage(String type, long id,
                                             String content);

    protected abstract void sendGroupMessage(String type, long id, String content);

    protected abstract void sendSessMessage(String type, long group,
                                            long sendid, String content);

    protected abstract void shutup(long parseLong, long parseLong2,
                                   int parseLong3);
}
