/*
 * 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.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;

public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
    // 定义查询文件夹笔记列表的令牌
    private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;

    // 定义查询文件夹列表的令牌
    private static final int FOLDER_LIST_QUERY_TOKEN      = 1;

    // 定义文件夹菜单的删除选项
    private static final int MENU_FOLDER_DELETE = 0;

    // 定义文件夹菜单的查看选项
    private static final int MENU_FOLDER_VIEW = 1;

    // 定义文件夹菜单的更改名称选项
    private static final int MENU_FOLDER_CHANGE_NAME = 2;

    // 定义首选项中添加介绍的键
    private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";

    // 定义列表编辑状态枚举
    private enum ListEditState {
        NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
    };

    // 当前列表编辑状态
    private ListEditState mState;

    // 后台查询处理器
    private BackgroundQueryHandler mBackgroundQueryHandler;

    // 笔记列表适配器
    private NotesListAdapter mNotesListAdapter;

    // 笔记列表视图
    private ListView mNotesListView;

    // 添加新笔记按钮
    private Button mAddNewNote;

    // 是否分发事件
    private boolean mDispatch;

    // 原始Y坐标
    private int mOriginY;

    // 分发Y坐标
    private int mDispatchY;

    // 标题栏
    private TextView mTitleBar;

    // 当前文件夹ID
    private long mCurrentFolderId;

    // 内容解析器
    private ContentResolver mContentResolver;

    // 多选模式回调
    private ModeCallback mModeCallBack;

    // 日志标签
    private static final String TAG = "NotesListActivity";

    // 笔记列表视图滚动速率
    public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;

    // 焦点笔记数据项
    private NoteItemData mFocusNoteDataItem;

    // 正常选择条件
    private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";

    // 根文件夹选择条件
    private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
            + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
            + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
            + NoteColumns.NOTES_COUNT + ">0)";

    // 打开笔记的请求代码
    private final static int REQUEST_CODE_OPEN_NODE = 102;
    // 新建笔记的请求代码
    private final static int REQUEST_CODE_NEW_NODE  = 103;

    @Override
    // 重写父类的方法，这里是重写Activity类的onCreate方法
    protected void onCreate(Bundle savedInstanceState) {
        // 调用父类的onCreate方法，确保Activity正常创建
        super.onCreate(savedInstanceState);
        // 设置当前Activity的布局文件为note_list.xml
        setContentView(R.layout.note_list);
        // 初始化资源，具体实现可能在initResources方法中定义
        initResources();

        /**
         * Insert an introduction when user firstly use this application
         */
        // 从原始资源文件中设置应用信息，可能是首次使用应用时的引导信息
        setAppInfoFromRawRes();
    }

    @Override
    // 重写父类的方法，处理从其他Activity返回的结果
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 检查返回结果是否为RESULT_OK，并且请求码为打开节点或新建节点
        if (resultCode == RESULT_OK
                && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
            // 如果条件满足，调用适配器的changeCursor方法，传入null，刷新数据
            mNotesListAdapter.changeCursor(null);
        } else {
            // 如果条件不满足，调用父类的onActivityResult方法，继续处理结果
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 从原始资源文件中设置应用信息的方法
    private void setAppInfoFromRawRes() {
        // 获取SharedPreferences实例，用于存储和读取应用偏好设置
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        // 检查是否已经添加了介绍信息，如果没有则进行添加
        if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
            // 创建StringBuilder用于构建读取的文本内容
            StringBuilder sb = new StringBuilder();
            InputStream in = null;
            try {
                // 打开原始资源文件，文件名为introduction
                 in = getResources().openRawResource(R.raw.introduction);
                // 检查输入流是否为空
                if (in != null) {
                    // 创建InputStreamReader和BufferedReader用于读取文件内容
                    InputStreamReader isr = new InputStreamReader(in);
                    BufferedReader br = new BufferedReader(isr);
                    // 创建字符数组用于存储读取的字符
                    char [] buf = new char[1024];
                    int len = 0;
                    // 循环读取文件内容，直到读取完毕
                    while ((len = br.read(buf)) > 0) {
                        // 将读取的字符追加到StringBuilder中
                        sb.append(buf, 0, len);
                    }
                } else {
                    // 如果输入流为空，则记录错误日志并返回
                    Log.e(TAG, "Read introduction file error");
                    return;
                }
            } catch (IOException e) {
                // 捕获IO异常并打印堆栈信息，然后返回
                e.printStackTrace();
                return;
            } finally {
                // 确保输入流被正确关闭
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            // 创建一个空的WorkingNote对象
            WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
                    AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
                    ResourceParser.RED);
            // 设置工作文本为读取的介绍信息
            note.setWorkingText(sb.toString());
            // 保存工作笔记
            if (note.saveNote()) {
                // 如果保存成功，更新SharedPreferences标记为已添加介绍信息
                sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
            } else {
                // 如果保存失败，记录错误日志并返回
                Log.e(TAG, "Save introduction note error");
                return;
            }
        }
    }

    @Override
    // 重写父类的方法，表示这个方法是一个覆盖方法
    protected void onStart() {
        // 调用父类的onStart方法，确保父类的逻辑得以执行
        super.onStart();
        // 调用startAsyncNotesListQuery方法，开始异步查询笔记列表
        startAsyncNotesListQuery();
    }

    // 初始化资源的方法
    private void initResources() {
        // 获取当前Activity的内容解析器
        mContentResolver = this.getContentResolver();
        // 创建一个后台查询处理器，用于在后台线程中执行查询操作
        mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
        // 设置当前文件夹ID为根文件夹ID
        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
        // 获取笔记列表视图
        mNotesListView = (ListView) findViewById(R.id.notes_list);
        // 向笔记列表视图添加一个页脚视图
        mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
                null, false);
        // 设置笔记列表项的点击监听器
        mNotesListView.setOnItemClickListener(new OnListItemClickListener());
        // 设置笔记列表项的长按监听器
        mNotesListView.setOnItemLongClickListener(this);
        // 创建并设置笔记列表适配器
        mNotesListAdapter = new NotesListAdapter(this);
        mNotesListView.setAdapter(mNotesListAdapter);
        // 获取添加新笔记的按钮
        mAddNewNote = (Button) findViewById(R.id.btn_new_note);
        // 设置添加新笔记按钮的点击监听器
        mAddNewNote.setOnClickListener(this);
        // 设置添加新笔记按钮的触摸监听器
        mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
        // 初始化触摸事件相关的变量
        mDispatch = false;
        mDispatchY = 0;
        mOriginY = 0;
        // 获取标题栏文本视图
        mTitleBar = (TextView) findViewById(R.id.tv_title_bar);
        // 设置当前状态为笔记列表状态
        mState = ListEditState.NOTE_LIST;
        // 创建并设置模式回调
        mModeCallBack = new ModeCallback();
    }

    // 定义一个内部类ModeCallback，实现ListView.MultiChoiceModeListener和OnMenuItemClickListener接口
    private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
        // 声明DropdownMenu对象，用于显示下拉菜单
        private DropdownMenu mDropDownMenu;
        // 声明ActionMode对象，用于多选模式
        private ActionMode mActionMode;
        // 声明MenuItem对象，用于移动菜单项
        private MenuItem mMoveMenu;

        // 当ActionMode创建时调用，初始化菜单和视图
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // 加载菜单布局
            getMenuInflater().inflate(R.menu.note_list_options, menu);
            // 设置删除菜单项的点击监听器
            menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
            // 获取移动菜单项
            mMoveMenu = menu.findItem(R.id.move);
            // 根据条件设置移动菜单项的可见性
            if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
                    || DataUtils.getUserFolderCount(mContentResolver) == 0) {
                mMoveMenu.setVisible(false);
            } else {
                mMoveMenu.setVisible(true);
                mMoveMenu.setOnMenuItemClickListener(this);
            }
            // 保存当前的ActionMode对象
            mActionMode = mode;
            // 设置笔记列表适配器为选择模式
            mNotesListAdapter.setChoiceMode(true);
            // 设置笔记列表不可长按
            mNotesListView.setLongClickable(false);
            // 隐藏添加新笔记的按钮
            mAddNewNote.setVisibility(View.GONE);

            // 加载自定义视图
            View customView = LayoutInflater.from(NotesListActivity.this).inflate(
                    R.layout.note_list_dropdown_menu, null);
            // 设置ActionMode的自定义视图
            mode.setCustomView(customView);
            // 初始化下拉菜单
            mDropDownMenu = new DropdownMenu(NotesListActivity.this,
                    (Button) customView.findViewById(R.id.selection_menu),
                    R.menu.note_list_dropdown);
            // 设置下拉菜单项的点击监听器
            mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
                public boolean onMenuItemClick(MenuItem item) {
                    // 切换全选/取消全选状态
                    mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
                    // 更新菜单
                    updateMenu();
                    return true;
                }

            });
            return true;
        }

        // 更新菜单标题和选项状态
        // 更新菜单项的方法
        private void updateMenu() {
            // 获取当前选中的笔记数量
            int selectedCount = mNotesListAdapter.getSelectedCount();
            // Update dropdown menu
            String format = getResources().getString(R.string.menu_select_title, selectedCount);
            mDropDownMenu.setTitle(format);
            MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
            if (item != null) {
                if (mNotesListAdapter.isAllSelected()) {
                    item.setChecked(true);
                    item.setTitle(R.string.menu_deselect_all);
                } else {
                    item.setChecked(false);
                    item.setTitle(R.string.menu_select_all);
                }
            }
        }

        // 定义一个方法，用于在ActionMode准备就绪时进行一些操作
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            // 这是一个自动生成的代码注释，提示开发者这里可以添加自定义逻辑
            // 返回false，表示没有对菜单进行任何修改
            return false;
        }

        // 定义一个方法，用于处理ActionMode中的菜单项点击事件
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // TODO Auto-generated method stub
            // 这是一个自动生成的代码注释，提示开发者此处需要实现具体的功能
            // 返回false，表示该点击事件未被处理
            return false;
        }

        // 当操作模式被销毁时调用的方法
        public void onDestroyActionMode(ActionMode mode) {
            // 设置笔记列表适配器的选择模式为false，即取消选择模式
            mNotesListAdapter.setChoiceMode(false);
            // 设置笔记列表视图的长按可点击性为true，即允许长按操作
            mNotesListView.setLongClickable(true);
            // 设置添加新笔记按钮的可见性为VISIBLE，即显示按钮
            mAddNewNote.setVisibility(View.VISIBLE);
        }

        // 定义一个公共方法，用于结束操作模式
        public void finishActionMode() {
            // 调用mActionMode对象的finish方法，结束当前的操作模式
            mActionMode.finish();
        }

        // 定义一个方法，当列表项的选中状态发生变化时被调用
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                boolean checked) {
            // 调用适配器的方法，设置指定位置项的选中状态
            mNotesListAdapter.setCheckedItem(position, checked);
            // 更新菜单，可能是为了根据选中状态显示或隐藏某些菜单项
            updateMenu();
        }

        // 定义一个方法来处理菜单项点击事件
        public boolean onMenuItemClick(MenuItem item) {
            // 检查当前选中的笔记数量是否为0
            if (mNotesListAdapter.getSelectedCount() == 0) {
                // 如果没有选中任何笔记，显示一个提示信息
                Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
                        Toast.LENGTH_SHORT).show();
                // 返回true表示事件已处理
                return true;
            }

            // 根据点击的菜单项ID进行不同的处理
            switch (item.getItemId()) {
                case R.id.delete:
                    // 创建一个AlertDialog.Builder对象来构建删除确认对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    // 设置对话框标题
                    builder.setTitle(getString(R.string.alert_title_delete));
                    // 设置对话框图标
                    builder.setIcon(android.R.drawable.ic_dialog_alert);
                    // 设置对话框消息，显示选中的笔记数量
                    builder.setMessage(getString(R.string.alert_message_delete_notes,
                                             mNotesListAdapter.getSelectedCount()));
                    // 设置对话框的确定按钮及其点击事件
                    builder.setPositiveButton(android.R.string.ok,
                                             new DialogInterface.OnClickListener() {
                                                 public void onClick(DialogInterface dialog,
                                                         int which) {
                                                     // 调用批量删除方法
                                                     batchDelete();
                                                 }
                                             });
                    // 设置对话框的取消按钮
                    builder.setNegativeButton(android.R.string.cancel, null);
                    // 显示对话框
                    builder.show();
                    break;
                case R.id.move:
                    // 调用方法查询目标文件夹
                    startQueryDestinationFolders();
                    break;
                default:
                    // 如果点击的菜单项ID不在上述范围内，返回false表示未处理
                    return false;
            }
            // 返回true表示事件已处理
            return true;
        }
    }

    // 定义一个内部类 NewNoteOnTouchListener，实现 OnTouchListener 接口，用于处理触摸事件
    private class NewNoteOnTouchListener implements OnTouchListener {

        // 重写 onTouch 方法，处理触摸事件
        public boolean onTouch(View v, MotionEvent event) {
            // 根据触摸事件的类型进行不同的处理
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    // 获取当前窗口的显示对象
                    Display display = getWindowManager().getDefaultDisplay();
                    // 获取屏幕的高度
                    int screenHeight = display.getHeight();
                    // 获取“新建笔记”按钮视图的高度
                    int newNoteViewHeight = mAddNewNote.getHeight();
                    // 计算触摸事件在屏幕中的起始位置
                    int start = screenHeight - newNoteViewHeight;
                    // 计算触摸事件的 Y 坐标
                    int eventY = start + (int) event.getY();
                    /**
                     * Minus TitleBar's height
                     */
                    if (mState == ListEditState.SUB_FOLDER) {
                        // 如果当前状态为子文件夹，减去标题栏的高度
                        eventY -= mTitleBar.getHeight();
                        start -= mTitleBar.getHeight();
                    }
                    /**
                     * HACKME:When click the transparent part of "New Note" button, dispatch
                     * the event to the list view behind this button. The transparent part of
                     * "New Note" button could be expressed by formula y=-0.12x+94（Unit:pixel）
                     * and the line top of the button. The coordinate based on left of the "New
                     * Note" button. The 94 represents maximum height of the transparent part.
                     * Notice that, if the background of the button changes, the formula should
                     * also change. This is very bad, just for the UI designer's strong requirement.
                     */
                    // 判断触摸点是否在“新建笔记”按钮的透明部分
                    if (event.getY() < (event.getX() * (-0.12) + 94)) {
                        // 获取列表视图中的最后一个子视图
                        View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
                                - mNotesListView.getFooterViewsCount());
                        if (view != null && view.getBottom() > start
                                && (view.getTop() < (start + 94))) {
                            // 记录原始触摸事件的 Y 坐标
                            mOriginY = (int) event.getY();
                            // 计算需要分发的 Y 坐标
                            mDispatchY = eventY;
                            // 设置触摸事件的新位置
                            event.setLocation(event.getX(), mDispatchY);
                            // 标记需要分发事件
                            mDispatch = true;
                            // 分发触摸事件到列表视图
                            return mNotesListView.dispatchTouchEvent(event);
                        }
                    }
                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    // 如果需要分发事件
                    if (mDispatch) {
                        // 更新需要分发的 Y 坐标
                        mDispatchY += (int) event.getY() - mOriginY;
                        // 设置触摸事件的新位置
                        event.setLocation(event.getX(), mDispatchY);
                        // 分发触摸事件到列表视图
                        return mNotesListView.dispatchTouchEvent(event);
                    }
                    break;
                }
                default: {
                    // 如果需要分发事件
                    if (mDispatch) {
                        // 设置触摸事件的新位置
                        event.setLocation(event.getX(), mDispatchY);
                        // 取消标记需要分发事件
                        mDispatch = false;
                        // 分发触摸事件到列表视图
                        return mNotesListView.dispatchTouchEvent(event);
                    }
                    break;
                }
            }
            // 默认返回 false，表示未处理该触摸事件
            return false;
        }

    };

    // 定义一个私有方法，用于启动异步的笔记列表查询
    private void startAsyncNotesListQuery() {
        // 根据当前文件夹ID是否为根文件夹，选择不同的查询条件
        // 如果当前文件夹ID等于根文件夹ID，则使用根文件夹的查询条件
        // 否则使用普通文件夹的查询条件
        String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
                : NORMAL_SELECTION;
        mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
                Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
                    String.valueOf(mCurrentFolderId)
                }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
    }

    // 定义一个私有的最终类 BackgroundQueryHandler，继承自 AsyncQueryHandler
    private final class BackgroundQueryHandler extends AsyncQueryHandler {
        // 构造函数，接收一个 ContentResolver 对象，并调用父类的构造函数
        public BackgroundQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        // 重写 onQueryComplete 方法，在查询完成时被调用
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            // 使用 switch 语句根据 token 的值来处理不同的查询结果
            switch (token) {
                case FOLDER_NOTE_LIST_QUERY_TOKEN:
                    // 如果 token 是 FOLDER_NOTE_LIST_QUERY_TOKEN，则更新 mNotesListAdapter 的数据源
                    mNotesListAdapter.changeCursor(cursor);
                    break;
                case FOLDER_LIST_QUERY_TOKEN:
                    // 如果 token 是 FOLDER_LIST_QUERY_TOKEN，则检查 cursor 是否不为空且包含数据
                    if (cursor != null && cursor.getCount() > 0) {
                        // 如果有数据，则显示文件夹列表菜单
                        showFolderListMenu(cursor);
                    } else {
                        // 如果没有数据，则记录错误日志
                        Log.e(TAG, "Query folder failed");
                    }
                    break;
                default:
                    // 如果 token 不匹配任何已知值，则直接返回
                    return;
            }
        }
    }

    // 定义一个私有方法showFolderListMenu，用于显示文件夹列表菜单
    private void showFolderListMenu(Cursor cursor) {
        // 创建一个AlertDialog.Builder对象，用于构建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
        // 设置对话框的标题，标题内容来自资源文件中的menu_title_select_folder
        builder.setTitle(R.string.menu_title_select_folder);
        // 创建一个FoldersListAdapter对象，用于适配文件夹列表数据
        final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
        // 设置对话框的适配器，用于显示文件夹列表
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

            // 当用户点击对话框中的某个选项时，执行此方法
            public void onClick(DialogInterface dialog, int which) {
                // 调用DataUtils的batchMoveToFolder方法，将选中的笔记批量移动到指定的文件夹
                DataUtils.batchMoveToFolder(mContentResolver,
                        mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
                // 显示一个Toast消息，提示用户笔记已移动到指定文件夹
                Toast.makeText(
                        NotesListActivity.this,
                        // 格式化字符串，显示移动的笔记数量和目标文件夹名称
                        getString(R.string.format_move_notes_to_folder,
                                mNotesListAdapter.getSelectedCount(),
                                adapter.getFolderName(NotesListActivity.this, which)),
                        // 设置Toast显示时长为短时间
                        Toast.LENGTH_SHORT).show();
                // 调用mModeCallBack的finishActionMode方法，结束当前的操作模式
                mModeCallBack.finishActionMode();
            }
        });
        // 显示对话框
        builder.show();
    }

    // 定义一个私有方法用于创建新笔记
    private void createNewNote() {
        // 创建一个Intent对象，用于从当前Activity跳转到NoteEditActivity
        Intent intent = new Intent(this, NoteEditActivity.class);
        // 设置Intent的动作类型为插入或编辑
        intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        // 向Intent中添加一个额外的数据，表示当前文件夹的ID
        intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
        // 调用startActivityForResult方法启动NoteEditActivity，并传递Intent和请求码
        // 请求码用于在NoteEditActivity返回结果时标识这次请求
        this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
    }

    // 定义一个私有方法batchDelete，用于批量删除选中的笔记
    private void batchDelete() {
        // 创建一个新的AsyncTask，用于在后台执行删除操作
        new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
            // 在后台执行删除操作
            protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
                // 获取选中的笔记对应的AppWidgetAttribute集合
                HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
                // 检查当前是否处于同步模式
                if (!isSyncMode()) {
                    // if not synced, delete notes directly
                    if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds())) {
                    } else {
                        Log.e(TAG, "Delete notes error, should not happens");
                    }
                } else {
                    // in sync mode, we'll move the deleted note into the trash
                    // folder
                    if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
                        Log.e(TAG, "Move notes to trash folder error, should not happens");
                    }
                }
                return widgets;
            }

            @Override
            protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
                if (widgets != null) {
                    for (AppWidgetAttribute widget : widgets) {
                        if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                                && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
                            updateWidget(widget.widgetId, widget.widgetType);
                        }
                    }
                }
                mModeCallBack.finishActionMode();
            }
        }.execute();
    }

    private void deleteFolder(long folderId) {
        if (folderId == Notes.ID_ROOT_FOLDER) {
            Log.e(TAG, "Wrong folder id, should not happen " + folderId);
            return;
        }

        HashSet<Long> ids = new HashSet<Long>();
        ids.add(folderId);
        HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
                folderId);
        if (!isSyncMode()) {
            // if not synced, delete folder directly
            DataUtils.batchDeleteNotes(mContentResolver, ids);
        } else {
            // in sync mode, we'll move the deleted folder into the trash folder
            DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
        }
        if (widgets != null) {
            for (AppWidgetAttribute widget : widgets) {
                if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                        && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
                    updateWidget(widget.widgetId, widget.widgetType);
                }
            }
        }
    }

    private void openNode(NoteItemData data) {
        Intent intent = new Intent(this, NoteEditActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra(Intent.EXTRA_UID, data.getId());
        this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
    }

    private void openFolder(NoteItemData data) {
        mCurrentFolderId = data.getId();
        startAsyncNotesListQuery();
        if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
            mState = ListEditState.CALL_RECORD_FOLDER;
            mAddNewNote.setVisibility(View.GONE);
        } else {
            mState = ListEditState.SUB_FOLDER;
        }
        if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
            mTitleBar.setText(R.string.call_record_folder_name);
        } else {
            mTitleBar.setText(data.getSnippet());
        }
        mTitleBar.setVisibility(View.VISIBLE);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_new_note:
                createNewNote();
                break;
            default:
                break;
        }
    }

    private void showSoftInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }

    private void hideSoftInput(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void showCreateOrModifyFolderDialog(final boolean create) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
        final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
        showSoftInput();
        if (!create) {
            if (mFocusNoteDataItem != null) {
                etName.setText(mFocusNoteDataItem.getSnippet());
                builder.setTitle(getString(R.string.menu_folder_change_name));
            } else {
                Log.e(TAG, "The long click data item is null");
                return;
            }
        } else {
            etName.setText("");
            builder.setTitle(this.getString(R.string.menu_create_folder));
        }

        builder.setPositiveButton(android.R.string.ok, null);
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                hideSoftInput(etName);
            }
        });

        final Dialog dialog = builder.setView(view).show();
        final Button positive = (Button)dialog.findViewById(android.R.id.button1);
        positive.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                hideSoftInput(etName);
                String name = etName.getText().toString();
                if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
                    Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
                            Toast.LENGTH_LONG).show();
                    etName.setSelection(0, etName.length());
                    return;
                }
                if (!create) {
                    if (!TextUtils.isEmpty(name)) {
                        ContentValues values = new ContentValues();
                        values.put(NoteColumns.SNIPPET, name);
                        values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                        values.put(NoteColumns.LOCAL_MODIFIED, 1);
                        mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
                                + "=?", new String[] {
                            String.valueOf(mFocusNoteDataItem.getId())
                        });
                    }
                } else if (!TextUtils.isEmpty(name)) {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.SNIPPET, name);
                    values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                    mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
                }
                dialog.dismiss();
            }
        });

        if (TextUtils.isEmpty(etName.getText())) {
            positive.setEnabled(false);
        }
        /**
         * When the name edit text is null, disable the positive button
         */
        etName.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(etName.getText())) {
                    positive.setEnabled(false);
                } else {
                    positive.setEnabled(true);
                }
            }

            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public void onBackPressed() {
        switch (mState) {
            case SUB_FOLDER:
                mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                mState = ListEditState.NOTE_LIST;
                startAsyncNotesListQuery();
                mTitleBar.setVisibility(View.GONE);
                break;
            case CALL_RECORD_FOLDER:
                mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                mState = ListEditState.NOTE_LIST;
                mAddNewNote.setVisibility(View.VISIBLE);
                mTitleBar.setVisibility(View.GONE);
                startAsyncNotesListQuery();
                break;
            case NOTE_LIST:
                super.onBackPressed();
                break;
            default:
                break;
        }
    }

    private void updateWidget(int appWidgetId, int appWidgetType) {
        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        if (appWidgetType == Notes.TYPE_WIDGET_2X) {
            intent.setClass(this, NoteWidgetProvider_2x.class);
        } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
            intent.setClass(this, NoteWidgetProvider_4x.class);
        } else {
            Log.e(TAG, "Unspported widget type");
            return;
        }

        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
            appWidgetId
        });

        sendBroadcast(intent);
        setResult(RESULT_OK, intent);
    }

    private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            if (mFocusNoteDataItem != null) {
                menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
                menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
                menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
                menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);
            }
        }
    };

    @Override
    public void onContextMenuClosed(Menu menu) {
        if (mNotesListView != null) {
            mNotesListView.setOnCreateContextMenuListener(null);
        }
        super.onContextMenuClosed(menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (mFocusNoteDataItem == null) {
            Log.e(TAG, "The long click data item is null");
            return false;
        }
        switch (item.getItemId()) {
            case MENU_FOLDER_VIEW:
                openFolder(mFocusNoteDataItem);
                break;
            case MENU_FOLDER_DELETE:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.alert_title_delete));
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setMessage(getString(R.string.alert_message_delete_folder));
                builder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                deleteFolder(mFocusNoteDataItem.getId());
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();
                break;
            case MENU_FOLDER_CHANGE_NAME:
                showCreateOrModifyFolderDialog(false);
                break;
            default:
                break;
        }

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (mState == ListEditState.NOTE_LIST) {
            getMenuInflater().inflate(R.menu.note_list, menu);
            // set sync or sync_cancel
            menu.findItem(R.id.menu_sync).setTitle(
                    GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
        } else if (mState == ListEditState.SUB_FOLDER) {
            getMenuInflater().inflate(R.menu.sub_folder, menu);
        } else if (mState == ListEditState.CALL_RECORD_FOLDER) {
            getMenuInflater().inflate(R.menu.call_record_folder, menu);
        } else {
            Log.e(TAG, "Wrong state:" + mState);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_new_folder: {
                showCreateOrModifyFolderDialog(true);
                break;
            }
            case R.id.menu_export_text: {
                exportNoteToText();
                break;
            }
            case R.id.menu_sync: {
                if (isSyncMode()) {
                    if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
                        GTaskSyncService.startSync(this);
                    } else {
                        GTaskSyncService.cancelSync(this);
                    }
                } else {
                    startPreferenceActivity();
                }
                break;
            }
            case R.id.menu_setting: {
                startPreferenceActivity();
                break;
            }
            case R.id.menu_new_note: {
                createNewNote();
                break;
            }
            case R.id.menu_search:
                onSearchRequested();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onSearchRequested() {
        startSearch(null, false, null /* appData */, false);
        return true;
    }

    private void exportNoteToText() {
        final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
        new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... unused) {
                return backup.exportToText();
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.failed_sdcard_export));
                    builder.setMessage(NotesListActivity.this
                            .getString(R.string.error_sdcard_unmounted));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                } else if (result == BackupUtils.STATE_SUCCESS) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.success_sdcard_export));
                    builder.setMessage(NotesListActivity.this.getString(
                            R.string.format_exported_file_location, backup
                                    .getExportedTextFileName(), backup.getExportedTextFileDir()));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.failed_sdcard_export));
                    builder.setMessage(NotesListActivity.this
                            .getString(R.string.error_sdcard_export));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                }
            }

        }.execute();
    }

    private boolean isSyncMode() {
        return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
    }

    private void startPreferenceActivity() {
        Activity from = getParent() != null ? getParent() : this;
        Intent intent = new Intent(from, NotesPreferenceActivity.class);
        from.startActivityIfNeeded(intent, -1);
    }

    private class OnListItemClickListener implements OnItemClickListener {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (view instanceof NotesListItem) {
                NoteItemData item = ((NotesListItem) view).getItemData();
                if (mNotesListAdapter.isInChoiceMode()) {
                    if (item.getType() == Notes.TYPE_NOTE) {
                        position = position - mNotesListView.getHeaderViewsCount();
                        mModeCallBack.onItemCheckedStateChanged(null, position, id,
                                !mNotesListAdapter.isSelectedItem(position));
                    }
                    return;
                }

                switch (mState) {
                    case NOTE_LIST:
                        if (item.getType() == Notes.TYPE_FOLDER
                                || item.getType() == Notes.TYPE_SYSTEM) {
                            openFolder(item);
                        } else if (item.getType() == Notes.TYPE_NOTE) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in NOTE_LIST");
                        }
                        break;
                    case SUB_FOLDER:
                    case CALL_RECORD_FOLDER:
                        if (item.getType() == Notes.TYPE_NOTE) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in SUB_FOLDER");
                        }
                        break;
                    default:
                        break;
                }
            }
        }

    }

    private void startQueryDestinationFolders() {
        String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
        selection = (mState == ListEditState.NOTE_LIST) ? selection:
            "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";

        mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
                null,
                Notes.CONTENT_NOTE_URI,
                FoldersListAdapter.PROJECTION,
                selection,
                new String[] {
                        String.valueOf(Notes.TYPE_FOLDER),
                        String.valueOf(Notes.ID_TRASH_FOLER),
                        String.valueOf(mCurrentFolderId)
                },
                NoteColumns.MODIFIED_DATE + " DESC");
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (view instanceof NotesListItem) {
            mFocusNoteDataItem = ((NotesListItem) view).getItemData();
            if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
                if (mNotesListView.startActionMode(mModeCallBack) != null) {
                    mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
                    mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                } else {
                    Log.e(TAG, "startActionMode fails");
                }
            } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
                mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
            }
        }
        return false;
    }
}
