package org.pulpdust.lesserpad;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Date;
//import java.util.regex.Pattern;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LesserPadActivity extends FragmentActivity implements TextWatcher {
	final static String TAG = "Lesser Pad Main";
	final static int FILE_NEW = 0;
	final static int FILE_OPEN = 1;
	final static String LPAD_EDIT = "org.pulpdust.lesserpad.EDIT";
	final static String LPAD_NEW = "org.pulpdust.lesserpad.NEW";
	static int fmode = 0;
	static int lmode;
	static boolean nosave = true;
	boolean oncreate = true;
	static File path;
	static String name = "";
	String default_dir;
	int cur_pos;
	float font_size;
	static int look_style;
	static EditText etxt;
	static Editable edit;
	Spinner ebox;
	static TextView label;
	static List<String> dirs = new ArrayList<String>();
	static ArrayAdapter<String> adirs;
	static String disuse = "[|:;*?<>/\\\\]";
//	Pattern notuse = Pattern.compile("[|:;*?<>/\\]");
	String undo_text;
	Integer undo_pos;
	Integer undo_mode;
	Integer undo_length;
	boolean undo_flag;
	Byte[] origin;
	static String action;
	String sname;
	int sfmode;
	
	public static class EditMemo extends EditText {
		private Rect rt;
		private Paint pt;
		
		public EditMemo(Context cn, AttributeSet as){
			super(cn, as);
			rt = new Rect();
			pt = new Paint();
			pt.setStyle(Paint.Style.STROKE);
			if (look_style > 0){
				pt.setColor(Color.rgb(68,68,68));
			} else {
				pt.setColor(Color.rgb(188,188,188));
			}
			pt.setPathEffect(new DashPathEffect(new float[]{ 2.0f, 2.0f }, 0));
		}
		@Override
		protected void onDraw(Canvas cv){
			int mhp = getMeasuredHeight() - getExtendedPaddingTop();
			int lh = getLineHeight();
			int dlc = mhp / lh;
			int lc = getLineCount();
			int count = Math.max(dlc, lc);
			Rect r = rt;
			Paint p = pt;
			int bl = getLineBounds(0, r);
			for (int i = 0; i < count; i++){
				cv.drawLine(r.left, bl + 1, r.right, bl + 1, p);
				bl = bl + lh;
			}
			super.onDraw(cv);
		}
	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        action = getIntent().getAction();
        readPrefs();
        if ((action.equals(Intent.ACTION_EDIT) || action.equals(Intent.ACTION_VIEW))
        		&& (Build.VERSION.SDK_INT < 11 || Build.VERSION.SDK_INT > 13)){
        	if (look_style >0){
        		setTheme(R.style.AppTheme_Dialog_Dark);
        	} else {
        		setTheme(R.style.AppTheme_Dialog);
        	}
       } else if (look_style > 0){ 
    		setTheme(R.style.AppTheme_Dark);
    	} else {
    		setTheme(R.style.AppTheme);
    	}
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        if (savedInstanceState == null){
        	fmode = FILE_NEW;
        	name = "";
        }
//        oncreate = true;
        if (action.equals(LPAD_NEW) || action.equals(Intent.ACTION_MAIN)){
        	this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        } else {
        	this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_UNCHANGED);
        }
        setContentView(R.layout.activity_lesser_pad);
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        	Toast.makeText(this, R.string.mes_nosd, Toast.LENGTH_LONG).show();
        	finish();
        }
        etxt = (EditText) findViewById(R.id.editText1);
    	etxt.setTextSize(font_size);
//        edit = etxt.getEditableText();
        etxt.addTextChangedListener(this);
        ebox = (Spinner) findViewById(R.id.spinner1);
        label = (TextView) findViewById(R.id.textView1);
        if (look_style > 0) label.setBackgroundResource(R.drawable.palmtitle_dark);
        adirs = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dirs);
        adirs.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ebox.setAdapter(adirs);
        label.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				openOptionsMenu();
			}
        });
        path = new File(Environment.getExternalStorageDirectory(), default_dir);
        if (!path.exists()){
        	path.mkdirs();
        }
//        name = "";
        if (Intent.ACTION_EDIT.equals(action) || 
        		Intent.ACTION_VIEW.equals(action) || 
        		LPAD_EDIT.equals(action)){
        	if (fileOpen(getIntent().getData())){
        		fmode = FILE_OPEN;
        		String gds = getIntent().getDataString();
        		if (gds.startsWith("file://")){
        			gds = gds.substring(7);
        		}
        		File fl = new File(gds);
        		try {
					path = new File(URLDecoder.decode(fl.getParent(), "UTF-8"));
	        		name = URLDecoder.decode(fl.getName(), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					Log.e(TAG, "hogeeeeeee!!!");
				}
        	} else {
        		Log.e(TAG, "fileOpen failed.");
        		Toast.makeText(this, R.string.mes_not_open, Toast.LENGTH_SHORT).show();
//        		fmode = FILE_NEW;
//        		name = "";
        	}
        	if (LPAD_EDIT.equals(action)){
        		lmode = 1;
        	} else {
        		lmode = 0;
        	}
        } else if (LPAD_NEW.equals(getIntent().getAction())){
        	path = new File(getIntent().getStringExtra("PATH"));
//        	fmode = FILE_NEW;
        	lmode = 1;
//        	name = "";
        } else {
//        	fmode = FILE_NEW;
        	lmode = 0;
//        	name="";
        }
        if (Build.VERSION.SDK_INT >= 11){
    		forHoneycomb.setEditText(etxt, this);
        	if ((!action.equals(Intent.ACTION_EDIT) && !action.equals(Intent.ACTION_VIEW))
        		|| (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= 13)){
        		ebox.setVisibility(View.GONE);
        		label.setVisibility(View.GONE);
        		forHoneycomb.setActionBar(this, 0, adirs);
        		if (fmode == FILE_NEW) forHoneycomb.setText(this, getString(R.string.label_new));
        		if (fmode == FILE_OPEN) forHoneycomb.setText(this, name);
        	}
        }
        if (fmode == FILE_NEW){
        	label.setText(R.string.label_new);
        } else if (fmode == FILE_OPEN && name != ""){
        	label.setText(name);
        } else {
        }
        listDir(path, adirs, dirs, ebox, this);
        ebox.setOnItemSelectedListener(new Mover());
        if (savedInstanceState == null){
        	if (cur_pos == 1){
        		etxt.setSelection(etxt.getText().length());
        		etxt.setSelection(0);
        	} else if (cur_pos == 2){
        		etxt.setSelection(etxt.getText().length());
        	}
        }
    	if (look_style > 0){
    		etxt.setTextColor(Color.rgb(190,190,190));
    		etxt.setHighlightColor(Color.rgb(0,0,255));
    		etxt.setBackgroundColor(Color.rgb(0,0,0));
    	} else if (look_style == 0){
    		etxt.setTextColor(Color.rgb(50,50,50));
    		etxt.setHighlightColor(Color.rgb(255,255,0));
    		etxt.setBackgroundColor(Color.rgb(255,255,255));
    	}
    }
    @Override
    public void onStart(){
    	super.onStart();
    	Log.d(TAG, "onStart");
    }
    @Override
    public void onResume(){
    	super.onResume();
    	Log.d(TAG, "onResume");
    }
    @Override
    public void onRestart(){
    	super.onRestart();
    	Log.d(TAG, "onRestart");
    }
    @Override
    public void onPause(){
    	super.onPause();
    	Log.d(TAG, "onPause");
    	if (fmode == FILE_OPEN){
    		Log.d(TAG, "oooo");
    	} else if (fmode == FILE_NEW){
    		Log.d(TAG, "nnnn");
    	}
    	if (fmode == FILE_OPEN && origin != null && Arrays.equals(origin, getSum(etxt.getText().toString()))){
    		nosave = true;
    	}
        if (fmode == FILE_NEW && etxt.getText().toString().length() == 0){
        	nosave = true;
        }
    	if (nosave){
    		
    	} else {
    		doSave();
    		nosave = true;
    	}
    }
    @Override
    public void onStop(){
    	super.onStop();
    	Log.d(TAG, "onStop");
    }
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	Log.d(TAG, "onDestroy");
    }
    public class Mover implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> av, View v, int pos,
				long id) {
			doMove(getApplicationContext(), pos);
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
    }
    public static void doMove(Context context, int pos){
		if (fmode == FILE_NEW){
			File base = path.getParentFile();
			path = new File(base, "/" + dirs.get(pos));
		} else if (fmode == FILE_OPEN && !path.getName().equals(dirs.get(pos))){
			String base = path.getParent();
			String newpath = base + "/" + dirs.get(pos);
			File from = new File(path, name);
			File to = new File(newpath, name);
			if (!to.exists() && from.renameTo(to)){
				path = new File(newpath);
			} else {
				Log.e(TAG, "onItemSelected::MoveFailed");
				Toast.makeText(context, R.string.mes_move_fail, Toast.LENGTH_SHORT).show();
			}
		}
    }
    public static void listDir(File path, ArrayAdapter<String> adirs, List<String> dirs, Spinner ebox, Activity av){
    	adirs.clear();
    	File base = path.getParentFile();
    	String cur = path.getName();
    	String list[] = base.list();
    	Arrays.sort(list);
    	for(int index = 0 ; index < list.length; index++){
    		File who = new File(base, list[index]);
    		if (who.isDirectory() && !list[index].matches("^\\.{1}.+$")){
    			adirs.add(list[index]);
    		}
    	}
    	int pos = dirs.indexOf(cur);
    	if (ebox != null){
    		ebox.setSelection(pos);
    	}
    	if (Build.VERSION.SDK_INT >= 11 && av != null){
    		if ((action != null && !action.equals(Intent.ACTION_EDIT) && !action.equals(Intent.ACTION_VIEW)) 
    				|| (action == null) 
    				|| (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= 13)){
    			forHoneycomb.setSelection(av, pos);
    		}
    	}
    }
    public Byte[] getSum(String text){
    	byte[] bin;
    	byte[] dg;
    	Byte[] ret;
    	if (text.equals("")){
    		dg = new byte[0];
    	} else {
    		bin = text.getBytes();
    		try {
    			MessageDigest md = MessageDigest.getInstance("SHA-512");
    			dg = md.digest(bin);
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			dg = new byte[0];
    		}
    	}
    	ret = new Byte[dg.length];
    	for (int i = 0; i < dg.length; i++){
    		ret[i] = dg[i];
    	}
    	return ret;
    }
    public boolean fileOpen(Uri uri){
    	String suri = uri.toString();
		if (suri.startsWith("file://")){
			suri = suri.substring(7);
		}
    	try {
        	File file = new File(URLDecoder.decode(suri, "UTF-8"));
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String content;
			content = br.readLine();
			String line;
			while ((line = br.readLine()) != null){
				content = content + "\n" + line;
			}
			if (content == null) content = "";
			origin = getSum(content);
			etxt.setText(content);
			br.close();
			return true;
		} catch (FileNotFoundException e) {
			Log.e(TAG, "fileOpen::NotFound");
			return false;
		} catch (UnsupportedEncodingException e){
			Log.e(TAG, "fileOpen::DecodeError");
			return false;
		} catch (IOException e) {
			Log.e(TAG, "fileOpen::IOError");
			return false;
		}
    }
    public void doSave(){
//    	final Handler hd = new Handler();
    	final Activity av = this;
//    	new Thread(new Runnable(){
//			@Override
//			public void run() {
	        	final boolean issave = textFiling();
//	        	hd.post(new Runnable(){
//	        		@Override
//	        		public void run(){
	                	if (issave == false){
	                		Log.d(TAG, "textFiling failed.");
	                		Toast.makeText(getApplicationContext(), R.string.mes_not_save, Toast.LENGTH_SHORT).show();
	                	} else {
	                		Toast.makeText(getApplicationContext(), R.string.mes_save, Toast.LENGTH_SHORT).show();
	                		fmode = FILE_OPEN;
	                		if (Build.VERSION.SDK_INT >= 11) forHoneycomb.setText(av, name);
	                		else label.setText(name);
	                	}
//	        		}
	        		
//	        	});
//			}
//    	}).start();
    }
    public boolean textFiling(){
        if (!path.exists()){
        	path.mkdirs();
        }
        String text = etxt.getText().toString();
        if (name.equals("")){
        	name = enTitle(0);
        } else {
        }
        File object = new File(path, name);
		while (fmode == FILE_NEW && object.exists()){
			name = enTitle(1);
			object = new File(path, name);
		}
        try {
			FileWriter fw = new FileWriter(object, false);
			text = text +"\n";
			fw.write(text);
			fw.close();
			origin = getSum(text);
			return true;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			return false;
		}
    }
    public static String enTitle(int mode){
    	String newname;
       String text = etxt.getText().toString();
       String lines[] = text.split("\n");
    	String rename = lines[0].replaceAll(disuse, "-");
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss-SSSZ");
        if (!lines[0].equals("") && mode == 0){
        	if (rename.length() > 62){
        		rename = rename.substring(0, 62);
        	}
            newname = rename + ".txt";
        } else if (!lines[0].equals("") && mode == 1){
        	if (rename.length() > 48){
        		rename = rename.substring(0, 48);
        	}
        	newname = rename + "-" + format.format(new Date()) + ".txt";
        } else if (lines[0].equals("")){
        	newname = format.format(new Date()) + ".txt";
        } else {
        	newname = "";
        }
    	return newname;
    }
    public void doCopy(CharSequence text){
    	if (Build.VERSION.SDK_INT >= 11){
    		forHoneycomb.doCopy(this, text);
    	} else {
    		ClipboardManager clipbd = (ClipboardManager)
				getSystemService(Context.CLIPBOARD_SERVICE);
    		clipbd.setText(text);
    	}
//		Toast.makeText(getApplicationContext(), getString(R.string.menu_copy) + ":" + text,
//				Toast.LENGTH_SHORT).show();
    }
    public CharSequence getCopy(){
		ClipboardManager clipbd = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    	return clipbd.getText();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
    	super.onPrepareOptionsMenu(menu);
    	if (Build.VERSION.SDK_INT >= 11){
    		forActionBarMenu(menu);
    		return true;
    	}
    	return true;
    }
    @TargetApi(11)
    public void forActionBarMenu(Menu menu){
    	if (Build.VERSION.SDK_INT >= 11){
    		MenuItem mix = (MenuItem) menu.findItem(R.id.menu_cut);
    		MenuItem mic = (MenuItem) menu.findItem(R.id.menu_copy);
    		MenuItem mif = (MenuItem) menu.findItem(R.id.menu_search);
    		mix.setVisible(false);
    		mic.setVisible(false);
    		mif.setVisible(false);
    	}
//    	if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= 13){
//    		MenuItem miv = (MenuItem) menu.findItem(R.id.menu_paste);
//    		MenuItem mia = (MenuItem) menu.findItem(R.id.menu_selectall);
//    		MenuItem miu = (MenuItem) menu.findItem(R.id.menu_undo);
//    		MenuItem mii = (MenuItem) menu.findItem(R.id.menu_detail);
//    		MenuItem mis = (MenuItem) menu.findItem(R.id.menu_share);
//    		MenuItem mid = (MenuItem) menu.findItem(R.id.menu_delete);
//    		MenuItem mip = (MenuItem) menu.findItem(R.id.menu_settings);
//    		miv.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		mia.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		miu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		mii.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		mis.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		mid.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    		mip.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//    	}
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	if (Build.VERSION.SDK_INT >= 11 && look_style > 0){
    		getMenuInflater().inflate(R.menu.activity_lesser_pad_dark, menu);
    	} else {
    		getMenuInflater().inflate(R.menu.activity_lesser_pad, menu);
    	}
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem mi){
    	switch (mi.getItemId()){
    	case R.id.menu_cut:
    		doCut();
    		return true;
    	case R.id.menu_copy:
    		todoCopy();
    		return true;
    	case R.id.menu_paste:
    		doPaste();
    		return true;
    	case R.id.menu_undo:
//    		if (undo_text != null && undo_pos != null){
//    			edit = etxt.getEditableText();
//    			edit.replace(0, edit.length(), undo_text);
//    			etxt.setSelection(undo_pos);
//    			undo_text = null;
//    			undo_pos = null;
//    		}
    		if (undo_mode != null && undo_pos != null && undo_text != null){
    			switch (undo_mode){
    			case 0:
    				edit = etxt.getEditableText();
    				edit.replace(undo_pos, undo_length, undo_text);
    				undo_mode = null;
    				break;
    			case 1:
    				edit = etxt.getEditableText();
    				edit.delete(undo_pos, undo_pos + undo_text.length());
    				undo_mode = null;
    				break;
    			}
    		}
    		return true;
    	case R.id.menu_selectall:
    		etxt.selectAll();
    		return true;
    	case R.id.menu_delete:
    		DialogFragment dd = DeleteDialog.newInstance(this);
    		dd.show(getSupportFragmentManager(), "fuga");
//    		sureDelete();
    		return true;
    	case R.id.menu_detail:
    		showDetail(this, this);
//    		echoDetail();
    		return true;
    	case R.id.menu_cancel:
    		nosave = true;
    		finish();
    		return true;
    	case R.id.menu_search:
    		goSearch(this);
    		return true;
    	case R.id.menu_share:
    		Intent intent = new Intent();
    		intent.setAction(Intent.ACTION_SEND);
    		intent.setType("text/plain");
    		intent.putExtra(Intent.EXTRA_TEXT, etxt.getText().toString());
    		startActivity(intent);
    		return true;
    	case R.id.menu_settings:
    		Intent goprefs = new Intent();
    		goprefs.setClassName("org.pulpdust.lesserpad", "org.pulpdust.lesserpad.LesserPadPrefs");
    		startActivityForResult(goprefs, 0);
    		return true;
    	case R.id.menu_ime:
    		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		imm.toggleSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0, 0);
    		return true;
    	default:
    		return super.onOptionsItemSelected(mi);
    	}
    }
    public static String getSelection(boolean deletion){
		edit = etxt.getEditableText();
		int start = etxt.getSelectionStart();
		int end = etxt.getSelectionEnd();
		char select[] = new char[Math.max( start, end ) - Math.min( start, end )];
		edit.getChars(Math.min( start, end ), Math.max( start, end ), select, 0);
		if (deletion){
			edit.delete(Math.min( start, end ), Math.max( start, end ));
		}
    	return String.valueOf(select);
    }
    public void doCut(){
    	String select = getSelection(true);
    	doCopy(select);
    }
    public void todoCopy(){
    	String select;
       select = getSelection(false);
		doCopy(select);
    }
    public void doPaste(){
		edit = etxt.getEditableText();
		int start = etxt.getSelectionStart();
		int end = etxt.getSelectionEnd();
		CharSequence obj;
		if (Build.VERSION.SDK_INT >= 11){
			obj = forHoneycomb.getCopy(this);
		} else {
			obj = getCopy();
		}
		if (obj != null){
			edit.replace(Math.min( start, end ), Math.max( start, end ), obj);
		}
    }
    
    public static void goSearch(Context context){
		Intent gosearch = new Intent();
		String forsearch = getSelection(false);
		gosearch.setAction(Intent.ACTION_SEARCH);
		gosearch.putExtra(SearchManager.QUERY, forsearch);
		gosearch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(gosearch);
    }
    public static class DetailDialog extends DialogFragment {
    	static Context cx;
    	public static DetailDialog newInstance(Context c){
    		DetailDialog dd = new DetailDialog();
    		cx = c;
    		return dd;
    	}
    	@Override
    	public Dialog onCreateDialog(Bundle savedInstanceState){
    		return echoDetail(cx, getActivity());
    	}
    }
    public static class DeleteDialog extends DialogFragment {
    	static Context cx;
    	public static DeleteDialog newInstance(Context c){
    		DeleteDialog dd = new DeleteDialog();
    		cx = c;
    		return dd;
    	}
    	@Override
    	public Dialog onCreateDialog(Bundle savedInstanceState){
    		return sureDelete(cx, getActivity());
    	}
    }
    public static void showDetail(Context c, FragmentActivity av){
		DialogFragment df = DetailDialog.newInstance(c);
		df.show(av.getSupportFragmentManager(), "hoge");
    }
    public static AlertDialog echoDetail(final Context c, final FragmentActivity av){
    	String update;
    	String dispname;
    	if (name.equals("")){
    		update = c.getString(R.string.dialog_presave);
    		dispname = c.getString(R.string.dialog_notfiled);
    	} else {
    		File object = new File(path, name);
    		update = DateUtils.formatDateTime(c, object.lastModified(), 
    		    DateUtils.FORMAT_SHOW_YEAR |
    		    DateUtils.FORMAT_SHOW_DATE |
    		    DateUtils.FORMAT_SHOW_TIME);
    		dispname = name;
    	}
    	AlertDialog.Builder builder = new AlertDialog.Builder(c);
    	builder.setMessage(c.getString(R.string.dialog_name)+": "+dispname+"\n"+c.getString(R.string.dialog_update)+": "+update+"\n"+
    			c.getString(R.string.dialog_length)+": "+etxt.length())
    			.setTitle(R.string.dialog_detail)
    			.setCancelable(true)
    			.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener(){
    				public void onClick(DialogInterface dialog, int id){
    					dialog.dismiss();
    				}
    			});
    	if (fmode == FILE_OPEN){
//    			final Activity av = this;
    			builder.setNeutralButton(R.string.dialog_rename, new DialogInterface.OnClickListener(){
    				public void onClick(DialogInterface dialog, int id){
    					String newname = enTitle(0);
    					if (!name.equals(newname)){
    						File from = new File(path, name);
    						File to = new File(path, newname);
    						while (to.exists()){
    							newname = enTitle(1);
    							to = new File(path, newname);
    						}
    						if (!to.exists() && from.renameTo(to)){
    							name = newname;
    							if (Build.VERSION.SDK_INT >= 11) forHoneycomb.setText(av, name);
    							else label.setText(name);
    							Toast.makeText(c, av.getString(R.string.mes_rename)+": "+name, Toast.LENGTH_SHORT).show();
    						} else {
    							Toast.makeText(c, R.string.mes_rename_fail, Toast.LENGTH_SHORT).show();
    						}
    					}
						dialog.dismiss();
//						showDetail(c, av);
//						echoDetail(c, av);
    				}
    			});
    	}
    	AlertDialog alert = builder.create();
    	return alert;
//    	alert.setOwnerActivity(this);
//    	alert.show();
    }
    public static AlertDialog sureDelete(final Context c, final Activity av){
    	AlertDialog.Builder builder = new AlertDialog.Builder(c);
    	builder.setMessage(c.getString(R.string.dialog_delete_sure))
    			.setTitle(R.string.dialog_delete)
    	       .setCancelable(false)
    	       .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   if (doDelete(path, name)){
    	        		   nosave = true;
    	       			if (lmode == 1){
    	    				Intent result = new Intent();
    	    				result.putExtra("PATH", path.toString());
    	    				av.setResult(RESULT_OK, result);
    	       			}
    	        		   av.finish();
    	        	   } else {
    	        		   Toast.makeText(c, R.string.mes_del_fail, Toast.LENGTH_SHORT).show();
    	        		   dialog.dismiss();
    	        	   }
    	           }
    	       })
    	       .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	return alert;
//    	alert.setOwnerActivity(this);
//    	alert.show();
    }
    public static boolean doDelete(File path, String name){
    	File object;
    	if (name == null){
    		object = new File(path.toString());
    	} else {
    		object = new File(path, name);
    	}
        if (object.delete()){
        	return true;
        } else {
        	return false;
        }
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent kev){
    	if (kev.getAction() == KeyEvent.ACTION_DOWN){
    		switch (kev.getKeyCode()){
    		case KeyEvent.KEYCODE_BACK:
    	    	if (fmode == FILE_OPEN && origin != null && Arrays.equals(origin, getSum(etxt.getText().toString()))){
    	    		nosave = true;
    	    	}
    	        if (fmode == FILE_NEW && etxt.getText().toString().length() == 0){
    	        	nosave = true;
    	        }
    			if (!nosave && etxt.getText().toString().length() != 0){
    			if (textFiling()){
    				Toast.makeText(getApplicationContext(), R.string.mes_save, Toast.LENGTH_SHORT).show();
    				nosave = true;
    			} else {
    				Toast.makeText(getApplicationContext(), R.string.mes_not_save, Toast.LENGTH_SHORT).show();
    				return true;
    			}
    			}
    			if (lmode == 1){
    				if (fmode == FILE_OPEN && etxt.getText().toString().length() == 0){
    					doDelete(path, name);
    					nosave = true;
    				}
    				Intent result = new Intent();
    				result.putExtra("PATH", path.toString());
    				setResult(RESULT_OK, result);
    				return super.dispatchKeyEvent(kev);
    			} else {
    				return super.dispatchKeyEvent(kev);
    			}
    		case KeyEvent.KEYCODE_MENU:
    			if (Build.VERSION.SDK_INT == 9 || Build.VERSION.SDK_INT == 10){
    				return true;
    			} else {
    				return super.dispatchKeyEvent(kev);
    			}
    		default:
    			return super.dispatchKeyEvent(kev);
    		}
    	} else if (kev.getAction() == KeyEvent.ACTION_UP){
    		switch(kev.getKeyCode()){
    		case KeyEvent.KEYCODE_SEARCH:
    			goSearch(this);
    			return true;
    		case KeyEvent.KEYCODE_MENU:
    			if (Build.VERSION.SDK_INT == 9 || Build.VERSION.SDK_INT == 10){
    				openOptionsMenu();
    				return true;
    			} else {
    				return super.dispatchKeyEvent(kev);
    			}
    		default:
    			return super.dispatchKeyEvent(kev);
    		}
    	} else {
    		return super.dispatchKeyEvent(kev);
    	}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	switch (requestCode){
    	case 0:
    		readPrefs();
        	etxt.setTextSize(font_size);
    		break;
    	
    	}
    }
    public void readPrefs(){
    	SharedPreferences sprefs = PreferenceManager.getDefaultSharedPreferences(this);
    	default_dir = sprefs.getString("default_dir", getString(R.string.app_default_dir));
    	cur_pos = Integer.parseInt(sprefs.getString("cur_pos", "1"));
    	font_size = Float.parseFloat(sprefs.getString("font_size", "18.0f"));
    	look_style = Integer.parseInt(sprefs.getString("look_style", "0"));

    }
	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
//		Log.d(TAG, s.toString());
		if (oncreate && s.length() == 0){
			oncreate = false;
			nosave = true;
		} else {
			nosave = false;
		}
	}
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
//		Log.d(TAG, s.toString());
		if (s.length() > 0){
			undo_mode = 0;
			undo_pos = start;
			undo_length = start + after;
			undo_text = s.toString().substring(undo_pos, undo_pos + count);
			undo_flag = true;
		} else {
			undo_flag = false;
		}
//		if (s.length() > 0){
//			undo_text = s.toString();
////			undo_pos = etxt.getSelectionStart();
//		}
//		if (after == 0 && s.length() > 0){
//			undo_pos = start + count;
//		}
//		if (after > 0 && s.length() > 0){
//			undo_pos = start + count;
//		}
	}
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
//		Log.d(TAG, s.toString());
		if (before == 0 && undo_flag){
//			undo_pos = start;
			undo_mode = 1;
			undo_pos = start;
			undo_text = s.toString().substring(start, start + count);
		}
	}
	
}
