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

// Google Tasks同步管理类，负责本地便签与Google Tasks的同步操作
package net.micode.notes.gtask.remote;

// Android基础组件导入
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

// 项目资源文件导入
import net.micode.notes.R;

// 数据模型和工具类导入
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils;

// JSON处理类导入
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

// Java集合类导入
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

// Google Tasks同步管理主类
public class GTaskManager {
    // 日志标签
    private static final String TAG = GTaskManager.class.getSimpleName();

    // 同步状态常量定义
    public static final int STATE_SUCCESS = 0;
    public static final int STATE_NETWORK_ERROR = 1;
    public static final int STATE_INTERNAL_ERROR = 2;
    public static final int STATE_SYNC_IN_PROGRESS = 3;
    public static final int STATE_SYNC_CANCELLED = 4;

    // 单例实例
    private static GTaskManager mInstance = null;

    // Activity上下文
    private Activity mActivity;

    // 应用上下文
    private Context mContext;

    // 内容解析器
    private ContentResolver mContentResolver;

    // 同步状态标志
    private boolean mSyncing;

    // 取消同步标志
    private boolean mCancelled;

    // 任务列表哈希表（gid -> TaskList）
    private HashMap<String, TaskList> mGTaskListHashMap;

    // 任务节点哈希表（gid -> Node）
    private HashMap<String, Node> mGTaskHashMap;

    // 元数据哈希表（gid -> MetaData）
    private HashMap<String, MetaData> mMetaHashMap;

    // 元数据任务列表
    private TaskList mMetaList;

    // 本地删除ID集合
    private HashSet<Long> mLocalDeleteIdMap;

    // Google任务ID到本地ID的映射
    private HashMap<String, Long> mGidToNid;

    // 本地ID到Google任务ID的映射
    private HashMap<Long, String> mNidToGid;

    // 私有构造函数
    private GTaskManager() {
        // 初始化同步状态标志
        mSyncing = false;
        mCancelled = false;

        // 初始化任务列表哈希表
        mGTaskListHashMap = new HashMap<String, TaskList>();

        // 初始化任务节点哈希表
        mGTaskHashMap = new HashMap<String, Node>();

        // 初始化元数据哈希表
        mMetaHashMap = new HashMap<String, MetaData>();

        // 初始化元数据任务列表
        mMetaList = null;

        // 初始化本地删除ID集合
        mLocalDeleteIdMap = new HashSet<Long>();

        // 初始化ID映射表
        mGidToNid = new HashMap<String, Long>();
        mNidToGid = new HashMap<Long, String>();
    }

    // 获取单例实例
    public static synchronized GTaskManager getInstance() {
        // 如果实例不存在则创建新实例
        if (mInstance == null) {
            mInstance = new GTaskManager();
        }
        return mInstance;
    }

    // 设置Activity上下文（用于获取认证令牌）
    public synchronized void setActivityContext(Activity activity) {
        mActivity = activity;
    }

    // 执行同步操作
    public int sync(Context context, GTaskASyncTask asyncTask) {
        // 检查是否正在同步
        if (mSyncing) {
            Log.d(TAG, "Sync is in progress");
            return STATE_SYNC_IN_PROGRESS;
        }

        // 初始化上下文和内容解析器
        mContext = context;
        mContentResolver = mContext.getContentResolver();

        // 设置同步状态标志
        mSyncing = true;
        mCancelled = false;

        // 清空各种缓存和映射表
        mGTaskListHashMap.clear();
        mGTaskHashMap.clear();
        mMetaHashMap.clear();
        mLocalDeleteIdMap.clear();
        mGidToNid.clear();
        mNidToGid.clear();

        try {
            // 获取GTask客户端实例
            GTaskClient client = GTaskClient.getInstance();
            client.resetUpdateArray();

            // 登录Google Tasks（如果未取消）
            if (!mCancelled) {
                if (!client.login(mActivity)) {
                    throw new NetworkFailureException("login google task failed");
                }
            }

            // 初始化任务列表
            asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
            initGTaskList();

            // 执行内容同步
            asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
            syncContent();
        } catch (NetworkFailureException e) {
            // 处理网络错误
            Log.e(TAG, e.toString());
            return STATE_NETWORK_ERROR;
        } catch (ActionFailureException e) {
            // 处理操作错误
            Log.e(TAG, e.toString());
            return STATE_INTERNAL_ERROR;
        } catch (Exception e) {
            // 处理其他异常
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return STATE_INTERNAL_ERROR;
        } finally {
            // 清理资源
            mGTaskListHashMap.clear();
            mGTaskHashMap.clear();
            mMetaHashMap.clear();
            mLocalDeleteIdMap.clear();
            mGidToNid.clear();
            mNidToGid.clear();
            mSyncing = false;
        }

        // 返回同步结果状态
        return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
    }

    // 初始化Google Tasks列表
    private void initGTaskList() throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled)
            return;

        // 获取GTask客户端实例
        GTaskClient client = GTaskClient.getInstance();
        try {
            // 获取任务列表JSON数组
            JSONArray jsTaskLists = client.getTaskLists();

            // 首先初始化元数据列表
            mMetaList = null;
            for (int i = 0; i < jsTaskLists.length(); i++) {
                // 获取任务列表JSON对象
                JSONObject object = jsTaskLists.getJSONObject(i);
                String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
                String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);

                // 检查是否为元数据文件夹
                if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
                    // 创建元数据任务列表
                    mMetaList = new TaskList();
                    mMetaList.setContentByRemoteJSON(object);

                    // 加载元数据
                    JSONArray jsMetas = client.getTaskList(gid);
                    for (int j = 0; j < jsMetas.length(); j++) {
                        object = (JSONObject) jsMetas.getJSONObject(j);
                        MetaData metaData = new MetaData();
                        metaData.setContentByRemoteJSON(object);
                        if (metaData.isWorthSaving()) {
                            mMetaList.addChildTask(metaData);
                            if (metaData.getGid() != null) {
                                mMetaHashMap.put(metaData.getRelatedGid(), metaData);
                            }
                        }
                    }
                }
            }

            // 如果元数据列表不存在则创建
            if (mMetaList == null) {
                mMetaList = new TaskList();
                mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
                        + GTaskStringUtils.FOLDER_META);
                GTaskClient.getInstance().createTaskList(mMetaList);
            }

            // 初始化普通任务列表
            for (int i = 0; i < jsTaskLists.length(); i++) {
                JSONObject object = jsTaskLists.getJSONObject(i);
                String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
                String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);

                // 检查是否为MIUI文件夹（非元数据文件夹）
                if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
                        && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
                        + GTaskStringUtils.FOLDER_META)) {
                    // 创建任务列表并添加到哈希表
                    TaskList tasklist = new TaskList();
                    tasklist.setContentByRemoteJSON(object);
                    mGTaskListHashMap.put(gid, tasklist);
                    mGTaskHashMap.put(gid, tasklist);

                    // 加载任务列表中的任务
                    JSONArray jsTasks = client.getTaskList(gid);
                    for (int j = 0; j < jsTasks.length(); j++) {
                        object = (JSONObject) jsTasks.getJSONObject(j);
                        gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
                        Task task = new Task();
                        task.setContentByRemoteJSON(object);
                        if (task.isWorthSaving()) {
                            task.setMetaInfo(mMetaHashMap.get(gid));
                            tasklist.addChildTask(task);
                            mGTaskHashMap.put(gid, task);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            // 处理JSON解析错误
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("initGTaskList: handing JSONObject failed");
        }
    }

    // 同步内容数据
    private void syncContent() throws NetworkFailureException {
        // 同步类型和临时变量
        int syncType;
        Cursor c = null;
        String gid;
        Node node;

        // 清空本地删除ID集合
        mLocalDeleteIdMap.clear();

        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 处理本地已删除的便签
        try {
            // 查询回收站中的便签
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
                    "(type<>? AND parent_id=?)", new String[] {
                            String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
                    }, null);
            if (c != null) {
                while (c.moveToNext()) {
                    // 获取Google任务ID和对应节点
                    gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 从哈希表中移除并执行同步
                        mGTaskHashMap.remove(gid);
                        doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
                    }

                    // 添加到本地删除集合
                    mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
                }
            } else {
                Log.w(TAG, "failed to query trash folder");
            }
        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // 首先同步文件夹
        syncFolder();

        // 处理数据库中存在的便签
        try {
            // 查询非回收站中的便签
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
                    "(type=? AND parent_id<>?)", new String[] {
                            String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
                    }, NoteColumns.TYPE + " DESC");
            if (c != null) {
                while (c.moveToNext()) {
                    // 获取Google任务ID和对应节点
                    gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 从哈希表中移除并确定同步类型
                        mGTaskHashMap.remove(gid);
                        mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
                        mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
                        syncType = node.getSyncAction(c);
                    } else {
                        // 根据情况确定是本地添加还是远程删除
                        if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
                            syncType = Node.SYNC_ACTION_ADD_REMOTE;
                        } else {
                            syncType = Node.SYNC_ACTION_DEL_LOCAL;
                        }
                    }
                    // 执行内容同步
                    doContentSync(syncType, node, c);
                }
            } else {
                Log.w(TAG, "failed to query existing note in database");
            }

        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // 处理剩余的项目（远程添加）
        Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Node> entry = iter.next();
            node = entry.getValue();
            doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
        }

        // 检查是否已取消（可能由其他线程设置）
        // 清理本地删除表
        if (!mCancelled) {
            if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
                throw new ActionFailureException("failed to batch-delete local deleted notes");
            }
        }

        // 刷新本地同步ID（如果未取消）
        if (!mCancelled) {
            GTaskClient.getInstance().commitUpdate();
            refreshLocalSyncId();
        }
    }

    // 同步文件夹
    private void syncFolder() throws NetworkFailureException {
        // 临时变量
        Cursor c = null;
        String gid;
        Node node;
        int syncType;

        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 处理根文件夹
        try {
            // 查询根文件夹
            c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
                    Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
            if (c != null) {
                c.moveToNext();
                // 获取Google任务ID和对应节点
                gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                node = mGTaskHashMap.get(gid);
                if (node != null) {
                    // 从哈希表中移除并更新映射
                    mGTaskHashMap.remove(gid);
                    mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
                    mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
                    // 对于系统文件夹，只在必要时更新远程名称
                    if (!node.getName().equals(
                            GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
                        doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
                } else {
                    doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
                }
            } else {
                Log.w(TAG, "failed to query root folder");
            }
        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // 处理通话记录文件夹
        try {
            // 查询通话记录文件夹
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
                    new String[] {
                            String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
                    }, null);
            if (c != null) {
                if (c.moveToNext()) {
                    // 获取Google任务ID和对应节点
                    gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 从哈希表中移除并更新映射
                        mGTaskHashMap.remove(gid);
                        mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
                        mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
                        // 对于系统文件夹，只在必要时更新远程名称
                        if (!node.getName().equals(
                                GTaskStringUtils.MIUI_FOLDER_PREFFIX
                                        + GTaskStringUtils.FOLDER_CALL_NOTE))
                            doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
                    } else {
                        doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
                    }
                }
            } else {
                Log.w(TAG, "failed to query call note folder");
            }
        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // 处理本地存在的文件夹
        try {
            // 查询非回收站中的文件夹
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
                    "(type=? AND parent_id<>?)", new String[] {
                            String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
                    }, NoteColumns.TYPE + " DESC");
            if (c != null) {
                while (c.moveToNext()) {
                    // 获取Google任务ID和对应节点
                    gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 从哈希表中移除并确定同步类型
                        mGTaskHashMap.remove(gid);
                        mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
                        mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
                        syncType = node.getSyncAction(c);
                    } else {
                        // 根据情况确定是本地添加还是远程删除
                        if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
                            syncType = Node.SYNC_ACTION_ADD_REMOTE;
                        } else {
                            syncType = Node.SYNC_ACTION_DEL_LOCAL;
                        }
                    }
                    // 执行内容同步
                    doContentSync(syncType, node, c);
                }
            } else {
                Log.w(TAG, "failed to query existing folder");
            }
        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // 处理远程添加的文件夹
        Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, TaskList> entry = iter.next();
            gid = entry.getKey();
            node = entry.getValue();
            if (mGTaskHashMap.containsKey(gid)) {
                mGTaskHashMap.remove(gid);
                doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
            }
        }

        // 如果未取消则提交更新
        if (!mCancelled)
            GTaskClient.getInstance().commitUpdate();
    }

    // 执行具体的内容同步操作
    private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 元数据临时变量
        MetaData meta;

        // 根据同步类型执行不同操作
        switch (syncType) {
            case Node.SYNC_ACTION_ADD_LOCAL:
                // 本地添加节点
                addLocalNode(node);
                break;
            case Node.SYNC_ACTION_ADD_REMOTE:
                // 远程添加节点
                addRemoteNode(node, c);
                break;
            case Node.SYNC_ACTION_DEL_LOCAL:
                // 本地删除节点
                meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
                if (meta != null) {
                    GTaskClient.getInstance().deleteNode(meta);
                }
                mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
                break;
            case Node.SYNC_ACTION_DEL_REMOTE:
                // 远程删除节点
                meta = mMetaHashMap.get(node.getGid());
                if (meta != null) {
                    GTaskClient.getInstance().deleteNode(meta);
                }
                GTaskClient.getInstance().deleteNode(node);
                break;
            case Node.SYNC_ACTION_UPDATE_LOCAL:
                // 更新本地节点
                updateLocalNode(node, c);
                break;
            case Node.SYNC_ACTION_UPDATE_REMOTE:
                // 更新远程节点
                updateRemoteNode(node, c);
                break;
            case Node.SYNC_ACTION_UPDATE_CONFLICT:
                // 更新冲突（目前简单使用本地更新）
                updateRemoteNode(node, c);
                break;
            case Node.SYNC_ACTION_NONE:
                // 无操作
                break;
            case Node.SYNC_ACTION_ERROR:
            default:
                // 未知操作类型错误
                throw new ActionFailureException("unkown sync action type");
        }
    }

    // 添加本地节点
    private void addLocalNode(Node node) throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 创建SQLite便签对象
        SqlNote sqlNote;
        if (node instanceof TaskList) {
            // 处理任务列表（文件夹）
            if (node.getName().equals(
                    GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
                // 根文件夹
                sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
            } else if (node.getName().equals(
                    GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
                // 通话记录文件夹
                sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
            } else {
                // 普通文件夹
                sqlNote = new SqlNote(mContext);
                sqlNote.setContent(node.getLocalJSONFromContent());
                sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
            }
        } else {
            // 处理普通便签
            sqlNote = new SqlNote(mContext);
            JSONObject js = node.getLocalJSONFromContent();
            try {
                // 处理便签ID冲突
                if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
                    JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
                    if (note.has(NoteColumns.ID)) {
                        long id = note.getLong(NoteColumns.ID);
                        if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
                            // ID不可用，需要创建新ID
                            note.remove(NoteColumns.ID);
                        }
                    }
                }

                // 处理数据ID冲突
                if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
                    JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject data = dataArray.getJSONObject(i);
                        if (data.has(DataColumns.ID)) {
                            long dataId = data.getLong(DataColumns.ID);
                            if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
                                // 数据ID不可用，需要创建新ID
                                data.remove(DataColumns.ID);
                            }
                        }
                    }
                }
            } catch (JSONException e) {
                Log.w(TAG, e.toString());
                e.printStackTrace();
            }
            sqlNote.setContent(js);

            // 设置父节点ID
            Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
            if (parentId == null) {
                Log.e(TAG, "cannot find task's parent id locally");
                throw new ActionFailureException("cannot add local node");
            }
            sqlNote.setParentId(parentId.longValue());
        }

        // 创建本地节点
        sqlNote.setGtaskId(node.getGid());
        sqlNote.commit(false);

        // 更新gid-nid映射
        mGidToNid.put(node.getGid(), sqlNote.getId());
        mNidToGid.put(sqlNote.getId(), node.getGid());

        // 更新元数据
        updateRemoteMeta(node.getGid(), sqlNote);
    }

    // 更新本地节点
    private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 创建SQLite便签对象
        SqlNote sqlNote;
        // 更新本地便签
        sqlNote = new SqlNote(mContext, c);
        sqlNote.setContent(node.getLocalJSONFromContent());

        // 设置父节点ID
        Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
                : new Long(Notes.ID_ROOT_FOLDER);
        if (parentId == null) {
            Log.e(TAG, "cannot find task's parent id locally");
            throw new ActionFailureException("cannot update local node");
        }
        sqlNote.setParentId(parentId.longValue());
        sqlNote.commit(true);

        // 更新元数据
        updateRemoteMeta(node.getGid(), sqlNote);
    }

    // 添加远程节点
    private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 创建SQLite便签对象
        SqlNote sqlNote = new SqlNote(mContext, c);
        Node n;

        // 远程更新
        if (sqlNote.isNoteType()) {
            // 处理普通便签
            Task task = new Task();
            task.setContentByLocalJSON(sqlNote.getContent());

            // 设置父任务列表
            String parentGid = mNidToGid.get(sqlNote.getParentId());
            if (parentGid == null) {
                Log.e(TAG, "cannot find task's parent tasklist");
                throw new ActionFailureException("cannot add remote task");
            }
            mGTaskListHashMap.get(parentGid).addChildTask(task);

            // 创建远程任务
            GTaskClient.getInstance().createTask(task);
            n = (Node) task;

            // 添加元数据
            updateRemoteMeta(task.getGid(), sqlNote);
        } else {
            // 处理文件夹
            TaskList tasklist = null;

            // 构建文件夹名称
            String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
            if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
                folderName += GTaskStringUtils.FOLDER_DEFAULT;
            else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
                folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
            else
                folderName += sqlNote.getSnippet();

            // 检查是否已存在同名文件夹
            Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, TaskList> entry = iter.next();
                String gid = entry.getKey();
                TaskList list = entry.getValue();

                if (list.getName().equals(folderName)) {
                    tasklist = list;
                    if (mGTaskHashMap.containsKey(gid)) {
                        mGTaskHashMap.remove(gid);
                    }
                    break;
                }
            }

            // 如果没有匹配则创建新文件夹
            if (tasklist == null) {
                tasklist = new TaskList();
                tasklist.setContentByLocalJSON(sqlNote.getContent());
                GTaskClient.getInstance().createTaskList(tasklist);
                mGTaskListHashMap.put(tasklist.getGid(), tasklist);
            }
            n = (Node) tasklist;
        }

        // 更新本地便签
        sqlNote.setGtaskId(n.getGid());
        sqlNote.commit(false);
        sqlNote.resetLocalModified();
        sqlNote.commit(true);

        // 更新gid-id映射
        mGidToNid.put(n.getGid(), sqlNote.getId());
        mNidToGid.put(sqlNote.getId(), n.getGid());
    }

    // 更新远程节点
    private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 创建SQLite便签对象
        SqlNote sqlNote = new SqlNote(mContext, c);

        // 远程更新
        node.setContentByLocalJSON(sqlNote.getContent());
        GTaskClient.getInstance().addUpdateNode(node);

        // 更新元数据
        updateRemoteMeta(node.getGid(), sqlNote);

        // 如果需要则移动任务
        if (sqlNote.isNoteType()) {
            Task task = (Task) node;
            TaskList preParentList = task.getParent();

            // 获取当前父任务列表
            String curParentGid = mNidToGid.get(sqlNote.getParentId());
            if (curParentGid == null) {
                Log.e(TAG, "cannot find task's parent tasklist");
                throw new ActionFailureException("cannot update remote task");
            }
            TaskList curParentList = mGTaskListHashMap.get(curParentGid);

            // 如果父任务列表发生变化则移动任务
            if (preParentList != curParentList) {
                preParentList.removeChildTask(task);
                curParentList.addChildTask(task);
                GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
            }
        }

        // 清除本地修改标志
        sqlNote.resetLocalModified();
        sqlNote.commit(true);
    }

    // 更新远程元数据
    private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
        // 只处理普通便签的元数据
        if (sqlNote != null && sqlNote.isNoteType()) {
            // 获取或创建元数据
            MetaData metaData = mMetaHashMap.get(gid);
            if (metaData != null) {
                // 更新现有元数据
                metaData.setMeta(gid, sqlNote.getContent());
                GTaskClient.getInstance().addUpdateNode(metaData);
            } else {
                // 创建新元数据
                metaData = new MetaData();
                metaData.setMeta(gid, sqlNote.getContent());
                mMetaList.addChildTask(metaData);
                mMetaHashMap.put(gid, metaData);
                GTaskClient.getInstance().createTask(metaData);
            }
        }
    }

    // 刷新本地同步ID
    private void refreshLocalSyncId() throws NetworkFailureException {
        // 检查是否已取消
        if (mCancelled) {
            return;
        }

        // 获取最新的Google任务列表
        mGTaskHashMap.clear();
        mGTaskListHashMap.clear();
        mMetaHashMap.clear();
        initGTaskList();

        // 查询并更新本地同步ID
        Cursor c = null;
        try {
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
                    "(type<>? AND parent_id<>?)", new String[] {
                            String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
                    }, NoteColumns.TYPE + " DESC");
            if (c != null) {
                while (c.moveToNext()) {
                    // 获取Google任务ID和对应节点
                    String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    Node node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 从哈希表中移除并更新同步ID
                        mGTaskHashMap.remove(gid);
                        ContentValues values = new ContentValues();
                        values.put(NoteColumns.SYNC_ID, node.getLastModified());
                        mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
                                c.getLong(SqlNote.ID_COLUMN)), values, null, null);
                    } else {
                        Log.e(TAG, "something is missed");
                        throw new ActionFailureException(
                                "some local items don't have gid after sync");
                    }
                }
            } else {
                Log.w(TAG, "failed to query local note to refresh sync id");
            }
        } finally {
            // 关闭Cursor
            if (c != null) {
                c.close();
                c = null;
            }
        }
    }

    // 获取同步账户名称
    public String getSyncAccount() {
        return GTaskClient.getInstance().getSyncAccount().name;
    }

    // 取消同步操作
    public void cancelSync() {
        mCancelled = true;
    }
}