/*
 * 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.gtask.remote;

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;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;


public class GTaskManager {
    private static final String TAG = GTaskManager.class.getSimpleName();
//定义了一些实例变量，如 mActivity、mContext、mContentResolver 等，以及一些数据结构，如 mGTaskListHashMap、mGTaskHashMap、mMetaHashMap 等，用于存储同步任务的相关信息。
    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;
//GTaskManager 采用单例模式，使用 getInstance() 方法获取实例。
    private static GTaskManager mInstance = null;

    private Activity mActivity; // 用于获取身份验证令牌
    private Context mContext;
    private ContentResolver mContentResolver;

    private boolean mSyncing; // 表示是否正在进行同步
    private boolean mCancelled; // 表示同步是否被取消

    // 存储 Google Tasks 列表的哈希映射
    private HashMap<String, TaskList> mGTaskListHashMap;

    // 存储 Google Tasks 节点（任务）的哈希映射
    private HashMap<String, Node> mGTaskHashMap;

    // 存储 Google Tasks 的元数据的哈希映射
    private HashMap<String, MetaData> mMetaHashMap;
    private TaskList mMetaList; // 元数据对应的任务列表

    // 存储本地已删除的任务ID
    private HashSet<Long> mLocalDeleteIdMap;

    // 存储 Google Tasks ID 到本地 ID 的哈希映射
    private HashMap<String, Long> mGidToNid;

    // 存储本地 ID 到 Google Tasks 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;
        mLocalDeleteIdMap = new HashSet<Long>();
        mGidToNid = new HashMap<String, Long>();
        mNidToGid = new HashMap<Long, String>();
    }

    public static synchronized GTaskManager getInstance() {
        if (mInstance == null) {
            mInstance = new GTaskManager();
        }
        return mInstance;
    }

    public synchronized void setActivityContext(Activity activity) {
        mActivity = activity;
    }

    // 同步方法，接收一个上下文对象和 GTaskASyncTask 对象
    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 {
            // 获取Google任务客户端实例并重置更新数组
            GTaskClient client = GTaskClient.getInstance();
            client.resetUpdateArray();

            // 登录Google任务
            if (!mCancelled) {
                if (!client.login(mActivity)) { // 如果登录失败
                    throw new NetworkFailureException("login google task failed"); // 抛出网络故障异常
                }
            }

            // 从Google获取任务列表
            asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); // 发布任务进度到UI线程
            initGTaskList(); // 初始化Google任务列表

            // 同步内容
            asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); // 发布任务进度到UI线程
            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 {
            // 清空任务列表HashMap、任务HashMap、元数据HashMap、本地删除ID映射、GID和NID映射，以及同步标记
            mGTaskListHashMap.clear();
            mGTaskHashMap.clear();
            mMetaHashMap.clear();
            mLocalDeleteIdMap.clear();
            mGidToNid.clear();
            mNidToGid.clear();
            mSyncing = false;
        }

        // 根据取消标记返回状态码
        return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
        }

        private void initGTaskList() throws NetworkFailureException {
            if (mCancelled) // 如果取消标记为true，则直接返回
                return;
            GTaskClient client = GTaskClient.getInstance();
            try {
                JSONArray jsTaskLists = client.getTaskLists(); // 获取任务列表

                // 首先初始化元数据列表
                mMetaList = null;
                for (int i = 0; i < jsTaskLists.length(); i++) {
                    JSONObject object = jsTaskLists.getJSONObject(i);
                    String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); // 获取任务列表的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); // 根据JSON数据填充元数据列表

                        // 加载元数据
                        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);
                            }
                        }
                    }
                }
            }

            // create meta list if not existed
             // create meta list if not existed
                if (mMetaList == null) { // 如果元列表不存在
                    mMetaList = new TaskList(); // 新建元列表
                    mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
                            + GTaskStringUtils.FOLDER_META); // 设置元列表名称
                    GTaskClient.getInstance().createTaskList(mMetaList); // 创建元列表
                }

                // init task list
                for (int i = 0; i < jsTaskLists.length(); i++) { // 遍历任务列表
                    JSONObject object = jsTaskLists.getJSONObject(i); // 获取任务列表对象
                    String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); // 获取任务列表ID
                    String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); // 获取任务列表名称

                    if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) // 如果任务列表以指定前缀开头
                            && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
                                    + GTaskStringUtils.FOLDER_META)) { // 并且不是元列表
                        TaskList tasklist = new TaskList(); // 新建任务列表
                        tasklist.setContentByRemoteJSON(object); // 从远程JSON设置任务列表内容
                        mGTaskListHashMap.put(gid, tasklist); // 将任务列表添加到哈希表中
                        mGTaskHashMap.put(gid, tasklist); // 将任务列表添加到哈希表中

                        // load tasks
                        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); // 获取任务ID
                            Task task = new Task(); // 新建任务
                            task.setContentByRemoteJSON(object); // 从远程JSON设置任务内容
                            if (task.isWorthSaving()) { // 如果值得保存
                                task.setMetaInfo(mMetaHashMap.get(gid)); // 设置任务的元信息
                                tasklist.addChildTask(task); // 添加任务到任务列表中
                                mGTaskHashMap.put(gid, task); // 将任务添加到哈希表中
                            }
                        }
                    }
                }
        } catch (JSONException e) {
            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;

        mLocalDeleteIdMap.clear();

        if (mCancelled) {
            return;
        }

        // for local deleted note
        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()) {
                    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 {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // sync folder first
        syncFolder();

        // for note existing in database
        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()) {
                    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) {
                            // local add
                            syncType = Node.SYNC_ACTION_ADD_REMOTE;
                        } else {
                            // remote delete
                            syncType = Node.SYNC_ACTION_DEL_LOCAL;
                        }
                    }
                    doContentSync(syncType, node, c);
                }
            } else {
                Log.w(TAG, "failed to query existing note in database");
            }

        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // go through remaining items
        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);
        }

        // mCancelled can be set by another thread, so we neet to check one by
        // one
        // clear local delete table
        if (!mCancelled) {
            if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
                throw new ActionFailureException("failed to batch-delete local deleted notes");
            }
        }

        // refresh local sync id
        if (!mCancelled) {
            GTaskClient.getInstance().commitUpdate();
            refreshLocalSyncId();
        }

    }

    private void syncFolder() throws NetworkFailureException {
        Cursor c = null;
        String gid;
        Node node;
        int syncType;

        if (mCancelled) {
            return;
        }

        // for root folder
        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();
                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);
                    // for system folder, only update remote name if necessary
                    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 {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // for call-note folder
        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()) {
                    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);
                        // for system folder, only update remote name if
                        // necessary
                        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 {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // for local existing folders
        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()) {
                    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) {
                            // local add
                            syncType = Node.SYNC_ACTION_ADD_REMOTE;
                        } else {
                            // remote delete
                            syncType = Node.SYNC_ACTION_DEL_LOCAL;
                        }
                    }
                    doContentSync(syncType, node, c);
                }
            } else {
                Log.w(TAG, "failed to query existing folder");
            }
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        // for remote add folders
        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; // 定义一个MetaData类型的变量
        switch (syncType) { // 根据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)); // 获取该节点的meta数据
                if (meta != null) {
                    GTaskClient.getInstance().deleteNode(meta); // 删除该节点的meta数据
                }
                mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); // 添加该节点的ID到本地删除ID Map中
                break;
            case Node.SYNC_ACTION_DEL_REMOTE: // 删除远程节点
                meta = mMetaHashMap.get(node.getGid()); // 获取该节点的meta数据
                if (meta != null) {
                    GTaskClient.getInstance().deleteNode(meta); // 删除该节点的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"); // 抛出一个ActionFailureException异常
        }
    }

    private void addLocalNode(Node node) throws NetworkFailureException { // 添加本地节点
        if (mCancelled) { // 如果已经取消，则直接返回
            return;
        }

        SqlNote sqlNote; // 定义一个SqlNote类型的变量
        if (node instanceof TaskList) { // 如果该节点是任务列表
            if (node.getName().equals( // 如果该节点的名称为MIUI_FOLDER_PREFFIX + FOLDER_DEFAULT
                    GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
                sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); // 创建一个根文件夹SqlNote
            } else if (node.getName().equals( // 如果该节点的名称为MIUI_FOLDER_PREFFIX + FOLDER_CALL_NOTE
                    GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
                sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); // 创建一个通话记录文件夹SqlNote
            } 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 {
                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)) {
                            // the id is not available, have to create a new one
                            note.remove(NoteColumns.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)) {
                                // the data id is not available, have to create
                                // a new one
                                data.remove(DataColumns.ID);
                            }
                        }
                    }

                }
            } catch (JSONException e) {
                Log.w(TAG, e.toString());
                e.printStackTrace();
            }
            sqlNote.setContent(js);

            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());
        }

        // create the local node
        sqlNote.setGtaskId(node.getGid());
        sqlNote.commit(false);

        // update gid-nid mapping
        mGidToNid.put(node.getGid(), sqlNote.getId());
        mNidToGid.put(sqlNote.getId(), node.getGid());

        // update meta
        updateRemoteMeta(node.getGid(), sqlNote);
    }

    private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
        if (mCancelled) {
            return;
        }

        SqlNote sqlNote;
        // update the note locally
        sqlNote = new SqlNote(mContext, c);
        sqlNote.setContent(node.getLocalJSONFromContent());

        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);

        // update meta info
        updateRemoteMeta(node.getGid(), sqlNote);
    }

    private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
        if (mCancelled) {
            return;
        }

        SqlNote sqlNote = new SqlNote(mContext, c);
        Node n;

        // update remotely
        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;

            // add meta
            updateRemoteMeta(task.getGid(), sqlNote);
        } else {
            TaskList tasklist = null;

            // we need to skip folder if it has already existed
            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;
                }
            }

            // no match we can add now
            if (tasklist == null) {
                tasklist = new TaskList();
                tasklist.setContentByLocalJSON(sqlNote.getContent());
                GTaskClient.getInstance().createTaskList(tasklist);
                mGTaskListHashMap.put(tasklist.getGid(), tasklist);
            }
            n = (Node) tasklist;
        }

        // update local note
        sqlNote.setGtaskId(n.getGid());
        sqlNote.commit(false);
        sqlNote.resetLocalModified();
        sqlNote.commit(true);

        // gid-id mapping
        mGidToNid.put(n.getGid(), sqlNote.getId());
        mNidToGid.put(sqlNote.getId(), n.getGid());
    }

    private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
        if (mCancelled) {
            return;
        }

        SqlNote sqlNote = new SqlNote(mContext, c);

        // update remotely
        node.setContentByLocalJSON(sqlNote.getContent());
        GTaskClient.getInstance().addUpdateNode(node);

        // update meta
        updateRemoteMeta(node.getGid(), sqlNote);

        // move task if necessary
        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);
            }
        }

        // clear local modified flag
        sqlNote.resetLocalModified();
        sqlNote.commit(true);
    }

    private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
        // 如果 SqlNote 是笔记类型的
        if (sqlNote != null && sqlNote.isNoteType()) {
            // 获取 gid 对应的 MetaData
            MetaData metaData = mMetaHashMap.get(gid);
            if (metaData != null) {
                // 更新 metaData 中 gid 对应的 meta 值
                metaData.setMeta(gid, sqlNote.getContent());
                // 将 metaData 加入到更新队列中
                GTaskClient.getInstance().addUpdateNode(metaData);
            } else {
                // 创建一个新的 MetaData
                metaData = new MetaData();
                metaData.setMeta(gid, sqlNote.getContent());
                // 将 metaData 加入到 MetaList 中，等待更新
                mMetaList.addChildTask(metaData);
                // 将 metaData 加入到 mMetaHashMap 中
                mMetaHashMap.put(gid, metaData);
                // 在 Google Tasks 中创建一个新任务
                GTaskClient.getInstance().createTask(metaData);
            }
        }
    }

    private void refreshLocalSyncId() throws NetworkFailureException {
        if (mCancelled) {
            return;
        }

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

        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()) {
                    // 获取本地笔记的 gid
                    String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
                    // 获取 gid 对应的 Google 任务节点
                    Node node = mGTaskHashMap.get(gid);
                    if (node != null) {
                        // 如果 Google 任务中存在该节点，则更新本地笔记的同步 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 {
                        // 如果 Google 任务中不存在该节点，则说明有同步问题，抛出异常
                        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 {
            if (c != null) {
                c.close();
                c = null;
            }
        }
    }

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

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

