package com.saki.plugin.dictionary;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.saki.QVMProtect;
import com.saki.qq.global.ScriptManager;
import com.saki.ui.DictionaryInputActivity;
import com.saki.ui.EditActivity;
import com.saki.sqv9.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
@QVMProtect
public class DictionaryView extends RelativeLayout implements OnClickListener,
        OnCheckedChangeListener {

    public static final String CONFIGNAME = "dictionary";
    public static final String CHARSET = "charset";
    public static final String BLACKLIST = "black";
    public static final String MASTER = "master";
    public static final String LEARN_PATTNER = "pattner";
    public static final String GROUP_REPLY = "G";
    public static final String BUDDY_REPLY = "B";
    public static final String DIS_REPLY = "D";
    public static final String SESS_REPLY = "S";
    Button blackadd;
    Button masterset;
    Button other;
    Button test;
    Button set;
    Button execEncode;
    Button e;
    EditText charset;
    EditText master;
    EditText black;
    TextView info;

    public DictionaryView(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.lay_dictionary, this);
        final TextView textView = (TextView) findViewById(R.id.textView3);
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());
        blackadd = (Button) findViewById(R.id.button2);
        masterset = (Button) findViewById(R.id.button3);
        other = (Button) findViewById(R.id.button4);
        test = (Button) findViewById(R.id.button5);
        set = (Button) findViewById(R.id.next);
        info = (TextView) findViewById(R.id.textView3);
        info.setMovementMethod(new ScrollingMovementMethod());
        execEncode = (Button) findViewById(R.id.button6);
        e = (Button) findViewById(R.id.button1);
        charset = (EditText) findViewById(R.id.editText1);
        charset.setText(getCharset());
        master = (EditText) findViewById(R.id.editText3);
        master.setText(getMaster());
        black = (EditText) findViewById(R.id.editText2);
        execEncode.setOnClickListener(this);
        blackadd.setOnClickListener(this);
        masterset.setOnClickListener(this);
        set.setOnClickListener(this);
        other.setOnClickListener(this);
        test.setOnClickListener(this);
        e.setOnClickListener(this);
    }

    @SuppressLint("NewApi")
    private boolean addDictionaryConfig(String key, String... s) {
        SharedPreferences sp = getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE);
        Editor e = sp.edit();
        Set<String> set = new HashSet<String>();
        sp.getStringSet(key, set);
        for (int i = -0; i < s.length; i++) {
            if (!set.contains(s[i]))
                set.add(s[i]);
        }
        e.putStringSet(key, set);
        return e.commit();
    }

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

    private boolean getDictionaryConfig(String key) {
        return getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE).getBoolean(key, false);
    }

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

    @SuppressLint("NewApi")
    private boolean inBlackList(String key, String value) {
        SharedPreferences sp = getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE);
        Set<String> set = new HashSet<String>();
        sp.getStringSet(key, set);
        return set.contains(value);
    }

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        ScriptManager.getInstance().getDictionary().dictionary.setCache(arg1);
        return;
    }

    @Override
    public void onClick(View v) {
        if (v == test) {
            Intent i = new Intent(getContext(), DictionaryInputActivity.class);
            getContext().startActivity(i);
        } else if (v == set) {
            String s = charset.getText().toString();
            if (s == null || s.equals("")) {
                Toast.makeText(getContext(), "请输入词库文本编码", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            try {
                new InputStreamReader(System.in, s);
            } catch (UnsupportedEncodingException e) {
                Toast.makeText(getContext(),
                        "非法字符编码！此字段不建议修改，请确认您已经了解此项功能的作用，并确实需要修改！",
                        Toast.LENGTH_LONG).show();
                return;
            }
            setDictionaryConfig(CHARSET, s);
        } else if (v == blackadd) {
            String s = black.getText().toString();
            if (s == null || s.equals("")) {
                Toast.makeText(getContext(), "请输入添加到黑名单的号码或群号",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (inBlackList(BLACKLIST, s)) {
                removeDictionaryConfig(BLACKLIST, s);
            } else {
                addDictionaryConfig(BLACKLIST, s);
            }
        } else if (v == masterset) {
            String s = master.getText().toString();
            if (s == null || s.equals("")) {
                Toast.makeText(getContext(), "请输入主人的号码", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            setDictionaryConfig(MASTER, s);
        } else if (v == other) {
            // 读取dic口令
            Dictionary dic = new Dictionary();
            try {
                dic.loadDictionary2Memory(getCharset());
                info.setText("");
                Iterator<String> it = dic.dic.keySet().iterator();
                while (it.hasNext()) {
                    info.append("[指令]:" + it.next() + "\r\n");
                }
            } catch (IOException e) {
                info.setText(e.toString());
            }
            return;
        } else if (v == execEncode) {
            Dictionary dic = new Dictionary();
            try {
                dic.loadDictionary2Memory(getCharset());
                dic.dicEncode();
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/SQ/dictionaryV8/dic_encode.txt");
                if (!f.exists()) {
                    f.getParentFile().mkdirs();
                    f.createNewFile();
                }
                dic.saveDictionary2File(f, getCharset());
                Toast.makeText(getContext(),"加密文件已保存:"+f.getAbsolutePath(),Toast.LENGTH_LONG).show();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (v == e) {
            getContext().startActivity(
                    new Intent(getContext(), EditActivity.class));
            return;
        }
        Toast.makeText(getContext(), "操作完成", Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("NewApi")
    private boolean removeDictionaryConfig(String key, String... s) {
        SharedPreferences sp = getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE);
        Editor e = sp.edit();
        Set<String> set = new HashSet<String>();
        sp.getStringSet(key, set);
        for (int i = 0; i < s.length; i++) {
            set.remove(s[i]);
        }
        e.putStringSet(key, set);
        return e.commit();
    }

    private boolean setDictionaryConfig(String key, boolean value) {
        SharedPreferences sp = getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE);
        Editor e = sp.edit();
        e.putBoolean(key, value);
        return e.commit();
    }

    private boolean setDictionaryConfig(String key, String value) {
        SharedPreferences sp = getContext().getSharedPreferences(CONFIGNAME,
                Context.MODE_PRIVATE);
        Editor e = sp.edit();
        e.putString(key, value);
        return e.commit();
    }

}
