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

import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

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.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;

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

import java.util.ArrayList;


/**
 * SqlNote - 用于管理笔记和相关数据的同步操作
 * 该类负责将笔记数据与 Google Tasks 进行同步，处理数据的创建、更新和删除操作
 */
public class SqlNote {
    private static final String TAG = SqlNote.class.getSimpleName();

    /**
     * 无效ID常量 - 用于标记未创建或无效的笔记ID
     */
    private static final int INVALID_ID = -99999;

    /**
     * 笔记查询投影数组 - 定义从数据库查询笔记时返回的列
     */
    public static final String[] PROJECTION_NOTE = new String[] {
            NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
            NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
            NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
            NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
            NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
            NoteColumns.VERSION
    };

    /**
     * 笔记ID列索引 - PROJECTION_NOTE数组中ID列的位置
     */
    public static final int ID_COLUMN = 0;

    /**
     * 提醒日期列索引 - PROJECTION_NOTE数组中提醒日期列的位置
     */
    public static final int ALERTED_DATE_COLUMN = 1;

    /**
     * 背景颜色ID列索引 - PROJECTION_NOTE数组中背景颜色ID列的位置
     */
    public static final int BG_COLOR_ID_COLUMN = 2;

    /**
     * 创建日期列索引 - PROJECTION_NOTE数组中创建日期列的位置
     */
    public static final int CREATED_DATE_COLUMN = 3;

    /**
     * 是否有附件列索引 - PROJECTION_NOTE数组中是否有附件列的位置
     */
    public static final int HAS_ATTACHMENT_COLUMN = 4;

    /**
     * 修改日期列索引 - PROJECTION_NOTE数组中修改日期列的位置
     */
    public static final int MODIFIED_DATE_COLUMN = 5;

    /**
     * 笔记数量列索引 - PROJECTION_NOTE数组中笔记数量列的位置
     */
    public static final int NOTES_COUNT_COLUMN = 6;

    /**
     * 父文件夹ID列索引 - PROJECTION_NOTE数组中父文件夹ID列的位置
     */
    public static final int PARENT_ID_COLUMN = 7;

    /**
     * 笔记摘要列索引 - PROJECTION_NOTE数组中笔记摘要列的位置
     */
    public static final int SNIPPET_COLUMN = 8;

    /**
     * 笔记类型列索引 - PROJECTION_NOTE数组中笔记类型列的位置
     */
    public static final int TYPE_COLUMN = 9;

    /**
     * 小部件ID列索引 - PROJECTION_NOTE数组中小部件ID列的位置
     */
    public static final int WIDGET_ID_COLUMN = 10;

    /**
     * 小部件类型列索引 - PROJECTION_NOTE数组中小部件类型列的位置
     */
    public static final int WIDGET_TYPE_COLUMN = 11;

    /**
     * 同步ID列索引 - PROJECTION_NOTE数组中同步ID列的位置
     */
    public static final int SYNC_ID_COLUMN = 12;

    /**
     * 本地修改状态列索引 - PROJECTION_NOTE数组中本地修改状态列的位置
     */
    public static final int LOCAL_MODIFIED_COLUMN = 13;

    /**
     * 原始父文件夹ID列索引 - PROJECTION_NOTE数组中原始父文件夹ID列的位置
     */
    public static final int ORIGIN_PARENT_ID_COLUMN = 14;

    /**
     * Google Tasks ID列索引 - PROJECTION_NOTE数组中Google Tasks ID列的位置
     */
    public static final int GTASK_ID_COLUMN = 15;

    /**
     * 版本号列索引 - PROJECTION_NOTE数组中版本号列的位置
     */
    public static final int VERSION_COLUMN = 16;

    /**
     * 上下文对象 - 用于访问应用资源和内容解析器
     */
    private Context mContext;

    /**
     * 内容解析器 - 用于访问ContentProvider进行数据操作
     */
    private ContentResolver mContentResolver;

    /**
     * 创建标志 - 标记笔记是否为新创建（未保存到数据库）
     */
    private boolean mIsCreate;

    /**
     * 笔记ID - 唯一标识一个笔记
     */
    private long mId;

    /**
     * 提醒日期 - 笔记的提醒时间戳
     */
    private long mAlertDate;

    /**
     * 背景颜色ID - 笔记的背景颜色资源ID
     */
    private int mBgColorId;

    /**
     * 创建日期 - 笔记创建的时间戳
     */
    private long mCreatedDate;

    /**
     * 是否有附件 - 标记笔记是否包含附件（0表示无，1表示有）
     */
    private int mHasAttachment;

    /**
     * 修改日期 - 笔记最后修改的时间戳
     */
    private long mModifiedDate;

    /**
     * 父文件夹ID - 笔记所属文件夹的ID
     */
    private long mParentId;

    /**
     * 笔记摘要 - 笔记内容的简短描述
     */
    private String mSnippet;

    /**
     * 笔记类型 - 区分笔记、文件夹、系统文件夹等类型
     */
    private int mType;

    /**
     * 小部件ID - 关联的应用小部件ID
     */
    private int mWidgetId;

    /**
     * 小部件类型 - 关联的应用小部件类型
     */
    private int mWidgetType;

    /**
     * 原始父文件夹ID - 笔记原始所属文件夹的ID（用于移动操作）
     */
    private long mOriginParent;

    /**
     * 版本号 - 用于处理并发编辑和同步冲突
     */
    private long mVersion;

    /**
     * 差异内容值 - 存储笔记属性的变更，用于数据库更新
     */
    private ContentValues mDiffNoteValues;

    /**
     * 数据列表 - 存储与笔记关联的详细内容数据
     */
    private ArrayList<SqlData> mDataList;

    /**
     * 构造函数 - 创建一个新的笔记对象
     * @param context 上下文对象
     */
    public SqlNote(Context context) {
        mContext = context;
        mContentResolver = context.getContentResolver();
        mIsCreate = true;
        mId = INVALID_ID;
        mAlertDate = 0;
        mBgColorId = ResourceParser.getDefaultBgId(context);
        mCreatedDate = System.currentTimeMillis();
        mHasAttachment = 0;
        mModifiedDate = System.currentTimeMillis();
        mParentId = 0;
        mSnippet = "";
        mType = Notes.TYPE_NOTE;
        mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
        mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
        mOriginParent = 0;
        mVersion = 0;
        mDiffNoteValues = new ContentValues();
        mDataList = new ArrayList<SqlData>();
    }

    /**
     * 构造函数 - 从数据库游标创建笔记对象
     * @param context 上下文对象
     * @param c 包含笔记数据的数据库游标
     */
    public SqlNote(Context context, Cursor c) {
        mContext = context;
        mContentResolver = context.getContentResolver();
        mIsCreate = false;
        loadFromCursor(c);
        mDataList = new ArrayList<SqlData>();
        if (mType == Notes.TYPE_NOTE)
            loadDataContent();
        mDiffNoteValues = new ContentValues();
    }

    /**
     * 构造函数 - 根据笔记ID创建笔记对象
     * @param context 上下文对象
     * @param id 笔记ID
     */
    public SqlNote(Context context, long id) {
        mContext = context;
        mContentResolver = context.getContentResolver();
        mIsCreate = false;
        loadFromCursor(id);
        mDataList = new ArrayList<SqlData>();
        if (mType == Notes.TYPE_NOTE)
            loadDataContent();
        mDiffNoteValues = new ContentValues();
    }

    /**
     * 根据ID从数据库加载笔记数据
     * @param id 笔记ID
     */
    private void loadFromCursor(long id) {
        Cursor c = null;
        try {
            c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
                    new String[] {
                        String.valueOf(id)
                    }, null);
            if (c != null) {
                c.moveToNext();
                loadFromCursor(c);
            } else {
                Log.w(TAG, "loadFromCursor: cursor = null");
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    /**
     * 从数据库游标加载笔记数据
     * @param c 包含笔记数据的游标
     */
    private void loadFromCursor(Cursor c) {
        mId = c.getLong(ID_COLUMN);
        mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
        mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
        mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
        mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
        mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
        mParentId = c.getLong(PARENT_ID_COLUMN);
        mSnippet = c.getString(SNIPPET_COLUMN);
        mType = c.getInt(TYPE_COLUMN);
        mWidgetId = c.getInt(WIDGET_ID_COLUMN);
        mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
        mVersion = c.getLong(VERSION_COLUMN);
    }

    /**
     * 加载笔记关联的数据内容
     * 从数据库查询与当前笔记关联的所有数据项
     */
    private void loadDataContent() {
        Cursor c = null;
        mDataList.clear();
        try {
            c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
                    "(note_id=?)", new String[] {
                        String.valueOf(mId)
                    }, null);
            if (c != null) {
                if (c.getCount() == 0) {
                    Log.w(TAG, "it seems that the note has not data");
                    return;
                }
                while (c.moveToNext()) {
                    SqlData data = new SqlData(mContext, c);
                    mDataList.add(data);
                }
            } else {
                Log.w(TAG, "loadDataContent: cursor = null");
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    /**
     * 从JSON对象设置笔记内容
     * @param js 包含笔记数据的JSON对象
     * @return 设置成功返回true，失败返回false
     */
    public boolean setContent(JSONObject js) {
        try {
            JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
            if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
                // 系统文件夹不允许修改
                Log.w(TAG, "cannot set system folder");
            } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
                // 对于文件夹，只能更新摘要和类型
                String snippet = note.has(NoteColumns.SNIPPET) ? note
                        .getString(NoteColumns.SNIPPET) : "";
                if (mIsCreate || !mSnippet.equals(snippet)) {
                    mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
                }
                mSnippet = snippet;

                int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
                        : Notes.TYPE_NOTE;
                if (mIsCreate || mType != type) {
                    mDiffNoteValues.put(NoteColumns.TYPE, type);
                }
                mType = type;
            } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
                // 对于普通笔记，更新所有属性并处理关联数据
                JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
                long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
                if (mIsCreate || mId != id) {
                    mDiffNoteValues.put(NoteColumns.ID, id);
                }
                mId = id;

                long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
                        .getLong(NoteColumns.ALERTED_DATE) : 0;
                if (mIsCreate || mAlertDate != alertDate) {
                    mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
                }
                mAlertDate = alertDate;

                int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
                        .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
                if (mIsCreate || mBgColorId != bgColorId) {
                    mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
                }
                mBgColorId = bgColorId;

                long createDate = note.has(NoteColumns.CREATED_DATE) ? note
                        .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
                if (mIsCreate || mCreatedDate != createDate) {
                    mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
                }
                mCreatedDate = createDate;

                int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
                        .getInt(NoteColumns.HAS_ATTACHMENT) : 0;
                if (mIsCreate || mHasAttachment != hasAttachment) {
                    mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
                }
                mHasAttachment = hasAttachment;

                long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
                        .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
                if (mIsCreate || mModifiedDate != modifiedDate) {
                    mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
                }
                mModifiedDate = modifiedDate;

                long parentId = note.has(NoteColumns.PARENT_ID) ? note
                        .getLong(NoteColumns.PARENT_ID) : 0;
                if (mIsCreate || mParentId != parentId) {
                    mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
                }
                mParentId = parentId;

                String snippet = note.has(NoteColumns.SNIPPET) ? note
                        .getString(NoteColumns.SNIPPET) : "";
                if (mIsCreate || !mSnippet.equals(snippet)) {
                    mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
                }
                mSnippet = snippet;

                int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
                        : Notes.TYPE_NOTE;
                if (mIsCreate || mType != type) {
                    mDiffNoteValues.put(NoteColumns.TYPE, type);
                }
                mType = type;

                int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                        : AppWidgetManager.INVALID_APPWIDGET_ID;
                if (mIsCreate || mWidgetId != widgetId) {
                    mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
                }
                mWidgetId = widgetId;

                int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
                        .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
                if (mIsCreate || mWidgetType != widgetType) {
                    mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
                }
                mWidgetType = widgetType;

                long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
                        .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
                if (mIsCreate || mOriginParent != originParent) {
                    mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
                }
                mOriginParent = originParent;

                // 处理关联的数据项
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject data = dataArray.getJSONObject(i);
                    SqlData sqlData = null;
                    // 查找是否已存在相同ID的数据项
                    if (data.has(DataColumns.ID)) {
                        long dataId = data.getLong(DataColumns.ID);
                        for (SqlData temp : mDataList) {
                            if (dataId == temp.getId()) {
                                sqlData = temp;
                            }
                        }
                    }

                    // 如果不存在，则创建新的数据项
                    if (sqlData == null) {
                        sqlData = new SqlData(mContext);
                        mDataList.add(sqlData);
                    }

                    // 设置数据项内容
                    sqlData.setContent(data);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 将笔记内容转换为JSON对象
     * @return 包含笔记数据的JSON对象，未创建的笔记返回null
     */
    public JSONObject getContent() {
        try {
            JSONObject js = new JSONObject();

            if (mIsCreate) {
                // 未保存到数据库的笔记无法获取完整内容
                Log.e(TAG, "it seems that we haven't created this in database yet");
                return null;
            }

            JSONObject note = new JSONObject();
            if (mType == Notes.TYPE_NOTE) {
                // 普通笔记包含所有属性和关联数据
                note.put(NoteColumns.ID, mId);
                note.put(NoteColumns.ALERTED_DATE, mAlertDate);
                note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
                note.put(NoteColumns.CREATED_DATE, mCreatedDate);
                note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
                note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
                note.put(NoteColumns.PARENT_ID, mParentId);
                note.put(NoteColumns.SNIPPET, mSnippet);
                note.put(NoteColumns.TYPE, mType);
                note.put(NoteColumns.WIDGET_ID, mWidgetId);
                note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
                note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
                js.put(GTaskStringUtils.META_HEAD_NOTE, note);

                // 添加关联的数据项
                JSONArray dataArray = new JSONArray();
                for (SqlData sqlData : mDataList) {
                    JSONObject data = sqlData.getContent();
                    if (data != null) {
                        dataArray.put(data);
                    }
                }
                js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
            } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
                // 文件夹和系统文件夹只包含基本属性
                note.put(NoteColumns.ID, mId);
                note.put(NoteColumns.TYPE, mType);
                note.put(NoteColumns.SNIPPET, mSnippet);
                js.put(GTaskStringUtils.META_HEAD_NOTE, note);
            }

            return js;
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置笔记的父文件夹ID
     * @param id 父文件夹ID
     */
    public void setParentId(long id) {
        mParentId = id;
        mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
    }

    /**
     * 设置Google Tasks ID
     * @param gid Google Tasks ID
     */
    public void setGtaskId(String gid) {
        mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
    }

    /**
     * 设置同步ID
     * @param syncId 同步ID
     */
    public void setSyncId(long syncId) {
        mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
    }

    /**
     * 重置本地修改状态
     * 将本地修改标记设置为0，表示没有本地修改
     */
    public void resetLocalModified() {
        mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
    }

    /**
     * 获取笔记ID
     * @return 笔记ID
     */
    public long getId() {
        return mId;
    }

    /**
     * 获取父文件夹ID
     * @return 父文件夹ID
     */
    public long getParentId() {
        return mParentId;
    }

    /**
     * 获取笔记摘要
     * @return 笔记摘要
     */
    public String getSnippet() {
        return mSnippet;
    }

    /**
     * 判断是否为笔记类型
     * @return 是笔记类型返回true，否则返回false
     */
    public boolean isNoteType() {
        return mType == Notes.TYPE_NOTE;
    }

    /**
     * 将笔记提交到数据库
     * @param validateVersion 是否验证版本号（用于处理并发编辑）
     */
    public void commit(boolean validateVersion) {
        if (mIsCreate) {
            // 创建新笔记
            // 如果ID无效且包含ID字段，则移除该字段（由数据库自动生成）
            if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
                mDiffNoteValues.remove(NoteColumns.ID);
            }

            // 插入新笔记到数据库
            Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
            try {
                // 从返回的URI中提取新生成的笔记ID
                mId = Long.valueOf(uri.getPathSegments().get(1));
            } catch (NumberFormatException e) {
                Log.e(TAG, "Get note id error :" + e.toString());
                throw new ActionFailureException("create note failed");
            }
            if (mId == 0) {
                throw new IllegalStateException("Create thread id failed");
            }

            // 如果是普通笔记，提交关联的数据项
            if (mType == Notes.TYPE_NOTE) {
                for (SqlData sqlData : mDataList) {
                    sqlData.commit(mId, false, -1);
                }
            }
        } else {
            // 更新现有笔记
            // 验证笔记ID的有效性（根文件夹和通话记录文件夹是特殊情况）
            if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
                Log.e(TAG, "No such note");
                throw new IllegalStateException("Try to update note with invalid id");
            }
            
            // 如果有需要更新的字段
            if (mDiffNoteValues.size() > 0) {
                mVersion ++; // 版本号递增
                int result = 0;
                if (!validateVersion) {
                    // 不验证版本号，直接更新
                    result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
                            + NoteColumns.ID + "=?)", new String[] {
                        String.valueOf(mId)
                    });
                } else {
                    // 验证版本号，确保不会覆盖并发编辑
                    result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
                            + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
                            new String[] {
                                    String.valueOf(mId), String.valueOf(mVersion)
                            });
                }
                if (result == 0) {
                    Log.w(TAG, "there is no update. maybe user updates note when syncing");
                }
            }

            // 如果是普通笔记，提交关联的数据项
            if (mType == Notes.TYPE_NOTE) {
                for (SqlData sqlData : mDataList) {
                    sqlData.commit(mId, validateVersion, mVersion);
                }
            }
        }

        // 刷新本地信息，确保与数据库保持一致
        loadFromCursor(mId);
        if (mType == Notes.TYPE_NOTE)
            loadDataContent();

        // 清除差异内容值并标记为已创建
        mDiffNoteValues.clear();
        mIsCreate = false;
    }
}
