/*
 * 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 {
    // 定义一个静态的UriMatcher对象，用于匹配URI
    private static final UriMatcher mMatcher;

    // 定义一个数据库帮助类对象
    private NotesDatabaseHelper mHelper;

    // 定义一个日志标签
    private static final String TAG = "NotesProvider";



    // 定义URI匹配常量
    private static final int URI_NOTE            = 1; // 匹配所有笔记
    private static final int URI_NOTE_ITEM       = 2; // 匹配单个笔记
    private static final int URI_DATA            = 3; // 匹配所有数据
    private static final int URI_DATA_ITEM       = 4; // 匹配单个数据

    private static final int URI_SEARCH          = 5; // 匹配搜索
    private static final int URI_SEARCH_SUGGEST  = 6; // 匹配搜索建议

    // 静态代码块，初始化UriMatcher
    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
    // 重写父类或接口中的onCreate方法
    public boolean onCreate() {
        // 定义一个方法，返回类型为boolean，用于初始化操作
        mHelper = NotesDatabaseHelper.getInstance(getContext());
        // 获取NotesDatabaseHelper的单例实例，并传入上下文对象
        // NotesDatabaseHelper.getInstance()：获取单例实例的方法
        // getContext()：获取当前上下文对象的方法
        return true;
        // 返回true，表示初始化成功
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        // 初始化游标对象
        Cursor c = null;
        // 获取可读数据库实例
        SQLiteDatabase db = mHelper.getReadableDatabase();
        // 初始化ID变量
        String id = null;
        // 根据URI匹配不同的查询类型
        switch (mMatcher.match(uri)) {
            case URI_NOTE:
                // 查询NOTE表
                c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
                        sortOrder);
                break;
            case URI_NOTE_ITEM:
                // 获取NOTE表中的特定ID
                id = uri.getPathSegments().get(1);
                // 查询NOTE表中ID匹配的记录
                c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs, null, null, sortOrder);
                break;
            case URI_DATA:
                // 查询DATA表
                c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
                        sortOrder);
                break;
            case URI_DATA_ITEM:
                // 获取DATA表中的特定ID
                id = uri.getPathSegments().get(1);
                // 查询DATA表中ID匹配的记录
                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;
                // 根据URI类型获取搜索字符串
                if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
                    if (uri.getPathSegments().size() > 1) {
                        searchString = uri.getPathSegments().get(1);
                    }
                } else {
                    searchString = uri.getQueryParameter("pattern");
                }

                // 如果搜索字符串为空，返回null
                if (TextUtils.isEmpty(searchString)) {
                    return null;
                }

                try {
                    // 格式化搜索字符串
                    searchString = String.format("%%%s%%", searchString);
                    // 执行原生SQL查询
                    c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
                            new String[] { searchString });
                } catch (IllegalStateException ex) {
                    // 记录异常信息
                    Log.e(TAG, "got exception: " + ex.toString());
                }
                break;
            default:
                // 抛出未知URI异常
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        // 如果游标不为空，设置通知URI
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        // 返回游标对象
        return c;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // 获取可写的数据库实例
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 初始化变量，用于存储插入后的ID
        long dataId = 0, noteId = 0, insertedId = 0;
        // 根据URI匹配不同的操作
        switch (mMatcher.match(uri)) {
            case URI_NOTE:
                // 插入到NOTE表，并获取插入的ID
                insertedId = noteId = db.insert(TABLE.NOTE, null, values);
                break;
            case URI_DATA:
                // 检查插入的值是否包含NOTE_ID
                if (values.containsKey(DataColumns.NOTE_ID)) {
                    // 获取NOTE_ID
                    noteId = values.getAsLong(DataColumns.NOTE_ID);
                } else {
                    // 如果没有NOTE_ID，记录错误日志
                    Log.d(TAG, "Wrong data format without note id:" + values.toString());
                }
                // 插入到DATA表，并获取插入的ID
                insertedId = dataId = db.insert(TABLE.DATA, null, values);
                break;
            default:
                // 如果URI不匹配，抛出异常
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        // Notify the note uri
        if (noteId > 0) {
            getContext().getContentResolver().notifyChange(
                    ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
        }

        // Notify the data uri
        if (dataId > 0) {
            getContext().getContentResolver().notifyChange(
                    ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
        }

        return ContentUris.withAppendedId(uri, insertedId);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // 初始化删除的记录数为0
        int count = 0;
        // 初始化记录ID为null
        String id = null;
        // 获取可写数据库实例
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 初始化是否删除数据的标志为false
        boolean deleteData = false;
        // 根据URI匹配不同的操作类型
        switch (mMatcher.match(uri)) {
            case URI_NOTE:
                // 为查询条件添加额外的限制：ID大于0
                selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
                // 执行删除操作并获取删除的记录数
                count = db.delete(TABLE.NOTE, selection, selectionArgs);
                break;
            case URI_NOTE_ITEM:
                // 从URI中获取具体的记录ID
                id = uri.getPathSegments().get(1);
                // 执行删除操作并获取删除的记录数
                long noteId = Long.valueOf(id);
                if (noteId <= 0) {
                    break;
                }

                count = db.delete(TABLE.NOTE,
                        NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
                break;
            case URI_DATA:
                count = db.delete(TABLE.DATA, selection, selectionArgs);
                deleteData = true;
                break;
            case URI_DATA_ITEM:
                id = uri.getPathSegments().get(1);
                count = db.delete(TABLE.DATA,
                        DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
                deleteData = true;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        if (count > 0) {
            if (deleteData) {
                // 如果删除的是数据，通知内容解析器数据已更改
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            }
            // 通知内容解析器指定URI的数据已更改
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        // 初始化更新记录的计数器
        int count = 0;
        // 初始化记录ID变量
        String id = null;
        // 获取可写数据库实例
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 标记是否更新了数据表
        boolean updateData = false;
        // 根据URI匹配不同的更新操作
        switch (mMatcher.match(uri)) {
            case URI_NOTE:
                // 增加笔记版本号，-1表示更新所有笔记
                increaseNoteVersion(-1, selection, selectionArgs);
                // 更新笔记表中的记录
                count = db.update(TABLE.NOTE, values, selection, selectionArgs);
                break;
            case URI_NOTE_ITEM:
                // 获取URI中的笔记ID
                id = uri.getPathSegments().get(1);
                // 增加指定笔记的版本号
                increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
                // 更新指定ID的笔记记录
                count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs);
                break;
            case URI_DATA:
                // 更新数据表中的记录
                count = db.update(TABLE.DATA, values, selection, selectionArgs);
                // 设置更新数据标记为true
                updateData = true;
                break;
            case URI_DATA_ITEM:
                // 获取URI中的数据ID
                id = uri.getPathSegments().get(1);
                // 更新指定ID的数据记录
                count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs);
                // 设置更新数据标记为true
                updateData = true;
                break;
            default:
                // 如果URI不匹配，抛出非法参数异常
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // 如果有记录被更新
        if (count > 0) {
            // 如果更新了数据表，通知内容解析器数据已更改
            if (updateData) {
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            }
            // 通知内容解析器指定URI的数据已更改
            getContext().getContentResolver().notifyChange(uri, null);
        }
        // 返回更新的记录数
        return count;
    }

    // 定义一个私有方法parseSelection，用于解析传入的选择条件字符串
    private String parseSelection(String selection) {
        // 使用三元运算符判断传入的选择条件字符串是否为空或仅包含空白字符
        // TextUtils.isEmpty(selection)用于检查字符串是否为空或仅包含空白字符
        // 如果selection不为空且不全是空白字符，则返回" AND (" + selection + ')'
        // 其中" AND ("和")"用于将传入的选择条件包裹起来，以便在SQL查询中使用
        // 如果selection为空或仅包含空白字符，则返回空字符串
        return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
    }

    // 增加笔记版本号的方法
    private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
        // 创建一个StringBuilder对象，用于构建SQL语句，初始容量为120
        StringBuilder sql = new StringBuilder(120);
        // 添加UPDATE语句和表名
        sql.append("UPDATE ");
        sql.append(TABLE.NOTE);
        sql.append(" SET ");
        // 设置版本号字段自增1
        sql.append(NoteColumns.VERSION);
        sql.append("=" + NoteColumns.VERSION + "+1 ");

        // 如果id大于0或者selection不为空，则添加WHERE子句
        if (id > 0 || !TextUtils.isEmpty(selection)) {
            sql.append(" WHERE ");
        }
        // 如果id大于0，则添加id的过滤条件
        if (id > 0) {
            sql.append(NoteColumns.ID + "=" + String.valueOf(id));
        }
        // 如果selection不为空，则处理selection字符串
        if (!TextUtils.isEmpty(selection)) {
            // 如果id大于0，则对selection进行解析
            String selectString = id > 0 ? parseSelection(selection) : selection;
            // 遍历selectionArgs数组，将selectString中的占位符替换为实际的参数值
            for (String args : selectionArgs) {
                selectString = selectString.replaceFirst("\\?", args);
            }
            // 将处理后的selectString添加到SQL语句中
            sql.append(selectString);
        }

        // 获取可写的数据库实例，并执行构建好的SQL语句
        mHelper.getWritableDatabase().execSQL(sql.toString());
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

}
