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


import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;


public class NotesProvider extends ContentProvider {//定义NotesProvider类，它继承自ContentProvider类
    private static final UriMatcher mMatcher;//声明UriMatcher实例

    private NotesDatabaseHelper mHelper;//声明NotesDatabaseHelper实例用于匹配Uri，以确定请求的类型，例如是否是请求特定的数据项，或者是否是搜索建议请求。

    private static final String TAG = "NotesProvider";

    private static final int URI_NOTE            = 1;//代表笔记数据的URI
    private static final int URI_NOTE_ITEM       = 2;//代表单个笔记数据的URI
    private static final int URI_DATA            = 3;//代表附加数据的URI
    private static final int URI_DATA_ITEM       = 4;//代表单个附加数据的URI

    private static final int URI_SEARCH          = 5;//代表搜索请求的URI
    private static final int URI_SEARCH_SUGGEST  = 6;//代表搜索建议请求的URI

    static {
        mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
        mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
        mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
        mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
        mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
        mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
        mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
    }

    /**
     * x'0A' represents the '\n' character in sqlite. For title and content in the search result,
     * we will trim '\n' and white space in order to show more information.
     */
    // 定义将在搜索结果中返回的列
    private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
        + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
        + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
        + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
        + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
        + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
        + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
    // 定义将执行以检索搜索结果的搜索查询
    private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
        + " FROM " + TABLE.NOTE// 指定要搜索的表
        + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"// 指定搜索查询
        + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER// 排除在垃圾桶文件夹中的笔记
        + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;// 排除非笔记条目

    @Override
    public boolean onCreate() {// 获取数据库帮助类的实例
        mHelper = NotesDatabaseHelper.getInstance(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        Cursor c = null;// 获取可读的数据库实例
        SQLiteDatabase db = mHelper.getReadableDatabase();
        String id = null;
        switch (mMatcher.match(uri)) {
            case URI_NOTE:// 查询所有笔记
                c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
                        sortOrder);
                break;
            case URI_NOTE_ITEM:// 查询单个笔记
                id = uri.getPathSegments().get(1);
                c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs, null, null, sortOrder);
                break;
            case URI_DATA:// 查询所有数据
                c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
                        sortOrder);
                break;
            case URI_DATA_ITEM: // 查询单个数据
                id = uri.getPathSegments().get(1);
                c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs, null, null, sortOrder);
                break;
            case URI_SEARCH:
            case URI_SEARCH_SUGGEST:// 搜索笔记
                if (sortOrder != null || projection != null) {
                    throw new IllegalArgumentException(
                            "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
                }

                String searchString = null;
                if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
                    if (uri.getPathSegments().size() > 1) {
                        searchString = uri.getPathSegments().get(1);
                    }
                } else {
                    searchString = uri.getQueryParameter("pattern");
                }

                if (TextUtils.isEmpty(searchString)) {
                    return null;
                }

                try {// 搜索所有匹配的笔记
                    searchString = String.format("%%%s%%", searchString);
                    c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
                            new String[] { searchString });
                } catch (IllegalStateException ex) {
                    Log.e(TAG, "got exception: " + ex.toString());
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        if (c != null) {// 设置通知URI，以便在数据更改时通知观察者
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {// 获取可写的 SQLiteDatabase 对象
        SQLiteDatabase db = mHelper.getWritableDatabase();// 初始化三个变量，用于存储 note、data 和插入的记录的 ID
        long dataId = 0, noteId = 0, insertedId = 0;// 根据传入的 Uri 进行匹配
        switch (mMatcher.match(uri)) {
            case URI_NOTE:// 向 TABLE.NOTE 表中插入记录，并获取插入的记录的 ID
                insertedId = noteId = db.insert(TABLE.NOTE, null, values);
                break;
            case URI_DATA:
                if (values.containsKey(DataColumns.NOTE_ID)) {// 如果 ContentValues 包含 DataColumns.NOTE_ID 列
                    noteId = values.getAsLong(DataColumns.NOTE_ID);// 获取 DataColumns.NOTE_ID 列的值
                } else {
                    Log.d(TAG, "Wrong data format without note id:" + values.toString());
                }//打印日志
                insertedId = dataId = db.insert(TABLE.DATA, null, values);// 向 TABLE.DATA 表中插入记录，并获取插入的记录的 ID
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);// 抛出 IllegalArgumentException 异常
        }
        // Notify the note uri
        if (noteId > 0) { // 如果 noteId 大于 0，则通知 content resolver 对应的 Uri 对应的数据已经发生了变化
            getContext().getContentResolver().notifyChange(
                    ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
        }

        // Notify the data uri
        if (dataId > 0) {// 如果 dataId 大于 0，则通知 content resolver 对应的 Uri 对应的数据已经发生了变化
            getContext().getContentResolver().notifyChange(
                    ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
        }

        return ContentUris.withAppendedId(uri, insertedId); // 返回插入的记录的 Uri
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        String id = null;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        boolean deleteData = false;
        switch (mMatcher.match(uri)) {// 根据传入的 Uri 进行匹配
            case URI_NOTE:// 如果匹配到 URI_NOTE
                selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";// 组合 selection 条件，以确保删除的是用户笔记，而不是系统文件夹
                count = db.delete(TABLE.NOTE, selection, selectionArgs);// 删除 TABLE.NOTE 表中符合条件的记录，并返回删除的数量
                break;
            case URI_NOTE_ITEM: // 如果匹配到 URI_NOTE_ITEM
                id = uri.getPathSegments().get(1);// 获取 Uri 中的 ID
                /**
                 * ID that smaller than 0 is system folder which is not allowed to
                 * trash
                 */
                long noteId = Long.valueOf(id);
                if (noteId <= 0) { // 如果 ID 小于等于 0，则直接跳出 switch 语句
                    break;
                }
                count = db.delete(TABLE.NOTE,
                        NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);// 删除 TABLE.NOTE 表中符合条件的记录，并返回删除的数量
                break;
            case URI_DATA:// 如果匹配到 URI_DATA
                count = db.delete(TABLE.DATA, selection, selectionArgs);// 删除 TABLE.DATA 表中符合条件的记录，并返回删除的数量
                deleteData = true;
                break;
            case URI_DATA_ITEM:// 如果匹配到 URI_DATA_ITEM
                id = uri.getPathSegments().get(1); // 获取 Uri 中的 ID
                count = db.delete(TABLE.DATA,
                        DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);// 删除 TABLE.DATA 表中符合条件的记录，并返回删除的数量
                deleteData = true;
                break;
            default:// 如果无法匹配到 Uri
                throw new IllegalArgumentException("Unknown URI " + uri);// 抛出 IllegalArgumentException 异常
        }
        if (count > 0) {// 如果删除的数量大于 0
            if (deleteData) {
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            } // 如果删除的是 TABLE.DATA 表中的记录，则通知 content resolver 对应的 Uri 对应的笔记数据已经发生了变化
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;// 返回删除的数量
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int count = 0;// 受影响的行数
        String id = null;// 被更新的笔记或数据项的ID
        SQLiteDatabase db = mHelper.getWritableDatabase();// 获取可写数据库
        boolean updateData = false;// 是否更新数据项

        switch (mMatcher.match(uri)) {// 使用 switch 语句处理不同类型的 URI
            case URI_NOTE:
                increaseNoteVersion(-1, selection, selectionArgs);// 在更新前增加所有受影响的笔记的版本号
                count = db.update(TABLE.NOTE, values, selection, selectionArgs);// 更新数据库中的行并获取受影响的行数

                break;
            case URI_NOTE_ITEM:
                id = uri.getPathSegments().get(1);// 在更新前增加笔记的版本号
                increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 更新数据库中的行并获取受影响的行数
                count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs);
                break;
            case URI_DATA:
                count = db.update(TABLE.DATA, values, selection, selectionArgs);
                updateData = true;
                break;
            case URI_DATA_ITEM:
                id = uri.getPathSegments().get(1);
                count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs);
                updateData = true;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        // 如果有行被更新，通知已注册的 ContentObserver
        if (count > 0) {
            if (updateData) {
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            }
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count; // 返回受影响的行数
    }
    // 辅助方法，如果传递了 selection 参数，则将其添加到 SQL 查询中
    private String parseSelection(String selection) {
        return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
    }
    // 辅助方法，在更新笔记之前增加其版本号
    private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
        StringBuilder sql = new StringBuilder(120);
        sql.append("UPDATE ");
        sql.append(TABLE.NOTE);
        sql.append(" SET ");
        sql.append(NoteColumns.VERSION);
        sql.append("=" + NoteColumns.VERSION + "+1 ");
        // 如果传递了 ID 或 selection 参数，则将其添加到 SQL 查询中
        if (id > 0 || !TextUtils.isEmpty(selection)) {
            sql.append(" WHERE ");
        }
        if (id > 0) {
            sql.append(NoteColumns.ID + "=" + String.valueOf(id));
        }
        if (!TextUtils.isEmpty(selection)) {
            String selectString = id > 0 ? parseSelection(selection) : selection;
            for (String args : selectionArgs) {
                selectString = selectString.replaceFirst("\\?", args);
            }
            sql.append(selectString);
        }

        mHelper.getWritableDatabase().execSQL(sql.toString());// 执行 SQL 查询以更新笔记的版本号
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub这是一个待办事项，需要根据 ContentProvider需求添加适当的 MIME类型。
        return null;
    }

}
