/*
 * 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;

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:" ;

    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
     */

    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;

    // 构造函数，用于创建一个NoteEditText对象
    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();
                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) {
            case KeyEvent.KEYCODE_ENTER:
                // 如果按下的是回车键
                if (mOnTextViewChangeListener != null) {

                    // 如果存在文本视图内容变化监听器
                    return false; // 不处理该按键事件，返回false
                }
                break; // 结束当前case
            case KeyEvent.KEYCODE_DEL:
                // 如果按下的是删除键
                mSelectionStartBeforeDelete = getSelectionStart();

                // 记录删除操作前的光标位置
                break; // 结束当前case
            default:

                // 如果是其他按键
                break; // 不做处理，直接结束当前case
        }
        // 调用父类的onKeyDown方法，处理其他按键事件
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // 根据按键代码进行不同的处理
        // 根据按键代码进行不同的处理
        switch(keyCode) {
                // 如果按键是删除键
            case KeyEvent.KEYCODE_DEL: // 处理删除键
                    // 如果设置了文本视图变化监听器
                // 如果设置了文本视图变化监听器
                if (mOnTextViewChangeListener != null) {
                    // 如果删除前的光标位置为0且当前索引不为0
                    if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
                        // 调用监听器的删除方法，传递当前索引和文本内容
                        mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
                        return true; // 返回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
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        // 检查是否有文本视图变化监听器
        if (mOnTextViewChangeListener != null) {
            // 如果当前视图失去焦点且文本为空
            if (!focused && TextUtils.isEmpty(getText())) {
                // 调用监听器的onTextChange方法，传递索引和false表示文本为空
                mOnTextViewChangeListener.onTextChange(mIndex, false);
            } else {
                // 否则调用监听器的onTextChange方法，传递索引和true表示文本不为空
                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) {
                int defaultResId = 0;
                for(String schema: sSchemaActionResMap.keySet()) {
                    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);
    }
}
