package com.saki.ui;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import com.saki.sqv9.R;
import com.saki.plugin.dictionary.DictionaryV8;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class EditActivity extends Activity implements OnClickListener {
    EditText e;
    TextView v;
    Button[] b = new Button[6];
    Button s;
    boolean save = true;
    String[] c = new String[]{"%", "$", ":", "=", "如果:\n如果尾", "\\r"};
    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                e.setText(msg.obj.toString());
                e.setSelection(e.getText().length());
                save = false;
            } else if (msg.what == 1) {
                int i = e.getSelectionStart();
                e.getText().insert(i, msg.obj.toString());
                if (msg.arg1 == -1) {
                    e.setSelection(e.getText().length());
                } else {
                    e.setSelection(i + msg.arg1);
                }
                save = false;
            } else {
                v.setText(msg.obj.toString());
            }
        }
    };

    private void append(String s, int i) {
        Message m = Message.obtain();
        m.what = 1;
        m.obj = s;
        m.arg1 = i;
        h.sendMessage(m);
    }

    private void info(String s) {
        Message m = Message.obtain();
        m.what = 2;
        m.obj = s;
        h.sendMessage(m);
    }

    @Override
    public void onClick(View v) {
        if (v == s) {
            String s = e.getText().toString();
            FileOutputStream o;
            try {
                o = new FileOutputStream(DictionaryV8.dicFile);
                o.write(s.getBytes("UTF-8"));
                o.flush();
                o.close();
            } catch (IOException e) {
                info("保存失败:" + e.getMessage());
            }
            info("保存完毕");
            save = true;
        }
        for (int i = 0; i < b.length; i++) {
            if (b[i] == v) {
                if (i == 4) {
                    append(c[i], 3);
                } else if (i == 5) {
                    append(c[i], 2);
                } else {
                    append(c[i], 1);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        e = (EditText) findViewById(R.id.editText1);
        s = (Button) findViewById(R.id.button6);
        v = (TextView) findViewById(R.id.textView1);
        b[0] = (Button) findViewById(R.id.button1);
        b[1] = (Button) findViewById(R.id.button2);
        b[2] = (Button) findViewById(R.id.button3);
        b[3] = (Button) findViewById(R.id.button4);
        b[4] = (Button) findViewById(R.id.button5);
        b[5] = (Button) findViewById(R.id.button7);
        new Thread(new Runnable() {
            @Override
            public void run() {
                info("正在打开dic...");
                try {
                    StringBuilder sb = new StringBuilder();
                    BufferedReader br = new BufferedReader(new FileReader(
                            DictionaryV8.dicFile));
                    String l = null;
                    while ((l = br.readLine()) != null)
                        sb.append(l + "\n");
                    set(sb.toString());
                    br.close();
                    info("读取完毕");
                } catch (IOException e) {
                    info("找不到dic文件/dic读取失败");
                }
            }
        }).start();
        s.setOnClickListener(this);
        for (int i = 0; i < b.length; i++) {
            b[i].setOnClickListener(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!save) {
                AlertDialog d = new AlertDialog.Builder(this)
                        .setTitle("警告")
                        .setMessage("当前dic未保存,退出将丢失所有进度，确定退出吗？")
                        .setNegativeButton("确定退出",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface arg0,
                                                        int arg1) {
                                        finish();
                                    }
                                }).setPositiveButton("取消", null).create();
                d.show();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void set(String s) {
        Message m = Message.obtain();
        m.what = 0;
        m.obj = s;
        h.sendMessage(m);
    }

}
