/*
 * 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;//这个类在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;

public class NoteEditText extends EditText {//继承edittext，设置便签设置文本框
    private static final String TAG = "NoteEditText";//定义常量标志为"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:" ;声明字符串常量，标志邮件

    private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();//建立一个字符和整数的hash表，用于链接电话,网站,邮箱
    static {//这个接口将会被NoteEditActivity实现来删除或添加编辑文本
        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
     */
    public interface OnTextViewChangeListener {//该接口用于实现对TextView组件中的文字信息进行修改
        /**
         * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
         * and the text is null
         */
        void onEditTextDelete(int index, String text);//当触发删除文本KeyEvent时删除文本

        /**
         * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
         * happen
         */
        void onEditTextEnter(int index, String text);//当触发输入文本KeyEvent时增添文本

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

    private OnTextViewChangeListener mOnTextViewChangeListener;//文本是否被改变

    public NoteEditText(Context context) {//构造函数,直接借用了父类的构造函数
        super(context, null);
        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);
    }

    public NoteEditText(Context context, AttributeSet attrs, int defStyle) {//构造函数,自动初始化
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    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 layout = getLayout();//用布局控件layout根据x,y的新值设置新的位置
                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) {//当用户按下按键瞬间系统的响应
        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) {//当用户松开按键瞬间系统的响应
        switch(keyCode) {
            case KeyEvent.KEYCODE_DEL://若触发修改且文档不为空，则调用前面代码的onEditTextDelete函数进行文本删除
                if (mOnTextViewChangeListener != null) {
                    if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
                        mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
                        return true;
                    }
                } else {//其他情况报错，文档的改动监听器并没有建立
                    Log.d(TAG, "OnTextViewChangeListener was not seted");
                }
                break;
            case KeyEvent.KEYCODE_ENTER://若文档改动监听器已建立，则获取当前位置和文本，并根据获取的信息调用onEditTextEnter函数进行文本增添
                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
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//这个函数规定了编辑文本焦点改变时的系统响应
        if (mOnTextViewChangeListener != null) {//若监听器已经建立
            if (!focused && TextUtils.isEmpty(getText())) {//获取到焦点并且文本不为空
                mOnTextViewChangeListener.onTextChange(mIndex, false);
            } else {
                mOnTextViewChangeListener.onTextChange(mIndex, 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);//获取开始到结尾的最大值

            final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);//针对不同的高亮元素，使用不同的操作进行处理
            if (urls.length == 1) {//设置url的信息的范围值
                int defaultResId = 0;
                for(String schema: sSchemaActionResMap.keySet()) {//获取计划表中所有的key值
                    if(urls[0].getURL().indexOf(schema) >= 0) {//若url可以添加则在添加后将defaultResId置为key所映射的值
                        defaultResId = sSchemaActionResMap.get(schema);
                        break;
                    }
                }

                if (defaultResId == 0) {//无改变则置为连接其他SchemaActionResMap的值
                    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);//执行父类的创建文本菜单
    }
}
