/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.content.Context;
import android.graphics.Rect;
import android.text.Layout;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.widget.EditText;

import net.micode.notes.R;

import java.util.HashMap;
import java.util.Map;
//继承edittext，设置便签设置文本框
public class NoteEditText extends EditText {
    private static final String TAG = "NoteEditText";
    private int mIndex;
    private int mSelectionStartBeforeDelete;

    private static final String SCHEME_TEL = "tel:" ;
    private static final String SCHEME_HTTP = "http:" ;
    private static final String SCHEME_EMAIL = "mailto:" ;

//定义了一个名为sSchemaActionResMap的静态常量map,构成字符串与整数的映射
//用于存储电话网站还有邮箱
    private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
    static {
        sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
        sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
        sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
    }

    /**
     * Call by the {@link NoteEditActivity} to delete or add edit text
     */

//在NoteEditActivity中删除或添加文本的操作，可以看做是一个文本是否被变的标记
    public interface OnTextViewChangeListener {
        /**
         * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
         * and the text is null
         */
        //在按下删除键且文本为空时删除当前编辑文本
        void onEditTextDelete(int index, String text);

        /**
         * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
         * happen
         */
        //在按下回车键时在当前编辑文本后添加编辑文本
        void onEditTextEnter(int index, String text);

        /**
         * Hide or show item option when text change
         */ 
        //在文本更改时隐藏或显示项目选项
        void onTextChange(int index, boolean hasText);
    }

    private OnTextViewChangeListener mOnTextViewChangeListener;


    //根据context设置文本
    public NoteEditText(Context context) {
        super(context, null);
        //用super引用父类变量
        mIndex = 0;
    }

    //光标设置
    public void setIndex(int index) {
        mIndex = index;
    }

    //初始化文本修改标记
    public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
        mOnTextViewChangeListener = listener;
    }

    //初始化便签
    public NoteEditText(Context context, AttributeSet attrs) {
        super(context, attrs, android.R.attr.editTextStyle);
    }

    // 根据defstyle自动初始化
    public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override 
    //重写函数
    //view里的函数
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {           
            //重写了需要处理屏幕被按下的事
            //改变坐标值
            case MotionEvent.ACTION_DOWN:
                int x = (int) event.getX();
                int y = (int) event.getY();
                x -= getTotalPaddingLeft();
                y -= getTotalPaddingTop();
                x += getScrollX();
                y += getScrollY();

                //用布局控件layout根据x,y的新值设置新的位置
                Layout layout = getLayout();
                int line = layout.getLineForVertical(y);
                int off = layout.getOffsetForHorizontal(line, x);
                
                //光标位置更新
                Selection.setSelection(getText(), off);
                break;
        }

        return super.onTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //根据按键的 Unicode 编码值来处理
        switch (keyCode) {
            //更具用户按下的keyCode是进入还是删除来处理事件
            case KeyEvent.KEYCODE_ENTER:
                if (mOnTextViewChangeListener != null) {
                    return false;
                }
                break;
            case KeyEvent.KEYCODE_DEL:
                mSelectionStartBeforeDelete = getSelectionStart();
                break;
            default:
                break;
        }
        //继续执行父类的其他点击事件
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        //根据按键的 Unicode 编码值来处理，有删除和进入2种操作
        switch(keyCode) {
            case KeyEvent.KEYCODE_DEL:   
            //当按键为删除键时，如果 mOnTextViewChangeListener 不为 null，则会检查当前光标位置是否为0且 mIndex不为0，则调用
                if (mOnTextViewChangeListener != null) {
                    if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
                        mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
                        //利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除
                        return true;
                    }
                } else {
                    //否则，会在日志中输出一条信息，表示文本视图更改监听器未设置。
                    Log.d(TAG, "OnTextViewChangeListener was not seted");
                }
                break;
            case KeyEvent.KEYCODE_ENTER: 
            //当按键为进入键时
                if (mOnTextViewChangeListener != null) {
                    int selectionStart = getSelectionStart();
                    //获取当前位置
                    String text = getText().subSequence(selectionStart, length()).toString();
                    //获取当前文本
                    setText(getText().subSequence(0, selectionStart));
                    //根据获取位置设置当前文本
                    mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
                } else {
                    Log.d(TAG, "OnTextViewChangeListener was not seted");
                    //其他情况报错，并输出文档的改动监听器并没有建立
                }
                break;
            default:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    //焦点变化时处理事件
    //focused表示是否获得焦点
    //direction表示焦点变化的方向
    //previouslyFocusedRect表示之前获得焦点视图的位置
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {

        if (mOnTextViewChangeListener != null) {
            //监听器已经建立
            if (!focused && TextUtils.isEmpty(getText())) {
            	//获取到焦点并且文本不为空
                mOnTextViewChangeListener.onTextChange(mIndex, false);
                //false则隐藏事件选项
            } else {
                mOnTextViewChangeListener.onTextChange(mIndex, true);
                //true则显示事件选项
            }
        }
    	//继续执行父类的其他焦点变化的事件
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override  
    //用于生成上下文菜单
    protected void onCreateContextMenu(ContextMenu menu) {
        //检查文本
        if (getText() instanceof Spanned) {
             // 获取选定文本的起始和结束位置
            int selStart = getSelectionStart();
            int selEnd = getSelectionEnd();

            // 计算选定文本的最小和最大位置
            int min = Math.min(selStart, selEnd);
            int max = Math.max(selStart, selEnd);

            // 获取选定文本中的所有 URLSpan
            final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
            //如果只有一个URLSpan
            if (urls.length == 1) {  
                int defaultResId = 0;
                //获取计划表中所有的key值  
                for(String schema: sSchemaActionResMap.keySet()) {
                	//若url可以添加则在添加后将defaultResId置为key所映射的值
                    if(urls[0].getURL().indexOf(schema) >= 0) {
                        defaultResId = sSchemaActionResMap.get(schema);
                        break;
                    }
                }

                if (defaultResId == 0) {
                    defaultResId = R.string.note_link_other;
                }
                //在菜单中增加选项
                menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
                        new OnMenuItemClickListener() {
                            public boolean onMenuItemClick(MenuItem item) {
                                // goto a new intent
                                urls[0].onClick(NoteEditText.this);
                                return true;
                            }
                        });
            }
        }
        //执行父类的其他菜单创建事件
        super.onCreateContextMenu(menu);
    }
}
