/*
 * 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 {// uri操作相关类，用于对数据库进行操作
    private static final UriMatcher mMatcher; // UriMatcher类用于分辨数据操作类型，用于匹配不同的uri

    private NotesDatabaseHelper mHelper; // 建立NotesDatabaseHelper类对象，用于数据库操作

    private static final String TAG = "NotesProvider"; // 设置类名标签，用于调试

    private static final int URI_NOTE = 1; // 设置便签uri
    private static final int URI_NOTE_ITEM = 2;
    private static final int URI_DATA = 3; // 设置数据uri
    private static final int URI_DATA_ITEM = 4;

    private static final int URI_SEARCH = 5; // 设置搜索uri
    private static final int URI_SEARCH_SUGGEST = 6;

    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);
    } // 将不同的uri与数值相匹配

    /**
     * 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.
     */ // 用0A代表\n，为搜索结果换行
    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; // 检索便签的sql语句，在列表中搜寻。使用Notes类中的接口与变量

    @Override
    public boolean onCreate() {
        mHelper = NotesDatabaseHelper.getInstance(getContext());
        return true; // 创建NotesDatabaseHelper类并返回成果标识
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) { // 负责查询数据，接受uri、返回烈、选择、排列方式
        Cursor c = null; // 创建空游标，表示数据库操作结果集合
        SQLiteDatabase db = mHelper.getReadableDatabase(); // 获取数据库对象
        String id = null;
        switch (mMatcher.match(uri)) { // 确定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; // 传参，对id进行查询
            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) { // 提取uri中搜索模式
                    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 }); // 在Notes表进行搜索
                } catch (IllegalStateException ex) {
                    Log.e(TAG, "got exception: " + ex.toString()); // 日志
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri); // 抛出异常
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri); // 在游标查询的数据变化时进行通知
        } // 通知uri是标识查询结果的uri，setNotificationUri方法可注册通知uri，与对象c相关联
        return c;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) { // uri表示要插入的uri，values表示要插入的数据,返回插入数据的uri
        SQLiteDatabase db = mHelper.getWritableDatabase(); // 打开或创建一个数据库
        long dataId = 0, noteId = 0, insertedId = 0;
        switch (mMatcher.match(uri)) { // 匹配uri
            case URI_NOTE:
                insertedId = noteId = db.insert(TABLE.NOTE, null, values); // 将数据插入到Notes表中
                break;
            case URI_DATA:
                if (values.containsKey(DataColumns.NOTE_ID)) { // 检查values是否含有NOTE_ID内容，返回bool值
                    noteId = values.getAsLong(DataColumns.NOTE_ID); // 关联noteId
                } else {
                    Log.d(TAG, "Wrong data format without note id:" + values.toString()); // 日志记录
                }
                insertedId = dataId = db.insert(TABLE.DATA, null, values); // 数据库插入新行的id返回到两个变量中
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        // Notify the note uri
        if (noteId > 0) { // 不为零表示插入成功，
            getContext().getContentResolver().notifyChange(
                    ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); // 通知uri发生变化
        }

        // Notify the data uri
        if (dataId > 0) {
            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) { // 表示要删除的uri、SQL中的WHERE与参数,返回删除的记录数
        int count = 0; // 表示删除记录数
        String id = null;
        SQLiteDatabase db = mHelper.getWritableDatabase(); // 打开数据库
        boolean deleteData = false;

        switch (mMatcher.match(uri)) { // uri匹配
            case URI_NOTE:
                selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; // 设置WHERE
                count = db.delete(TABLE.NOTE, selection, selectionArgs); // 删除，并计数
                break;
            case URI_NOTE_ITEM:
                id = uri.getPathSegments().get(1); // 获取id
                /**
                 * ID that smaller than 0 is system folder which is not allowed to
                 * trash
                 */
                long noteId = Long.valueOf(id);
                if (noteId <= 0) {
                    break;
                }
                count = db.delete(TABLE.NOTE,
                        NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
                break; // 删除指定id，并计数
            case URI_DATA:
                count = db.delete(TABLE.DATA, selection, selectionArgs); // 删除，并计数
                deleteData = true;
                break;
            case URI_DATA_ITEM:
                id = uri.getPathSegments().get(1); // 获取id
                count = db.delete(TABLE.DATA,
                        DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
                deleteData = true; // 删除指定id，并计数
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri); // 报错
        }

        if (count > 0) { // 表示有删除操作，通知uri发生变化
            if (deleteData) {
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            }
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count; // 返回删除的记录数
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // 表示更新的uri、values为新的列值、where以及参数
        int count = 0; // 更新条数
        String id = null;
        SQLiteDatabase db = mHelper.getWritableDatabase(); // 打开数据库
        boolean updateData = false; // 设置数据表更新表示
        switch (mMatcher.match(uri)) { // 匹配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); // 提取id
                increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
                count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs); // 增加指定的id条件
                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); // 抛出异常
        }

        if (count > 0) {
            if (updateData) {
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);// 通知指定uri数据更改
            }
            getContext().getContentResolver().notifyChange(uri, null); // 通知uri数据更改
        }
        return count;
    }

    private String parseSelection(String selection) { // 检查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 "); // 升级便签版本号

        if (id > 0 || !TextUtils.isEmpty(selection)) { // selection不为空或存在id则增加where条件
            sql.append(" WHERE ");
        }
        if (id > 0) {
            sql.append(NoteColumns.ID + "=" + String.valueOf(id));
        }
        if (!TextUtils.isEmpty(selection)) {
            String selectString = id > 0 ? parseSelection(selection) : selection; // parseSelection将传入的参数中的占位符替换为实际的值
            for (String args : selectionArgs) { //
                selectString = selectString.replaceFirst("\\?", args); // replaceFirst选择参数数组中的值替换语句中的占位符
            }
            sql.append(selectString);
        }

        mHelper.getWritableDatabase().execSQL(sql.toString()); // 执行SQL语句
    }

    @Override
    public String getType(Uri uri) { // 获取指定uri的MIME类型
        // TODO Auto-generated method stub //表示该方法没有实现
        return null;
    }
}
