/*
 * 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;//以下 引用android自带的类，包括数据库等
import android.content.ContentProvider;//导入ContentProvider
import android.content.ContentUris;//导入ContentUris
import android.content.ContentValues;//导入contentvalues
import android.content.Intent;//导入intent
import android.content.UriMatcher;//导入UriMatcher
import android.database.Cursor;//查询数据库所需的游标
import android.database.sqlite.SQLiteDatabase;//引入SQLite数据库
import android.net.Uri;
import android.text.TextUtils;//文本识别处理工具
import android.util.Log;

import net.micode.notes.R;//访问、删除、插入、更新、扩展Notes的数据库
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 {//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
    private static final UriMatcher mMatcher;//UriMatcher用于匹配Uri

    private NotesDatabaseHelper mHelper;//数据库辅助类的实例化

    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;
    private static final int URI_DATA_ITEM       = 4;

    private static final int URI_SEARCH          = 5;
    private static final int URI_SEARCH_SUGGEST  = 6;

    static {//代码段：这是一个注册URI路径的过程
        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);//SUGGEST_URI_PATH_QUERY 并不属于URI的一部分，而应是用于指向此路径的常量。
        mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
    }//注册完需要匹配的Uri后，就可以使用sMatcher.match(uri)方法对输入的Uri进行匹配

    /**
     * x'0A' represents the '\n' character in sqlite. For title and content in the search result,//trim()函数是去掉字符串头尾空格的函数
     * 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,//查询uri在数据库中对应的位置
            String sortOrder) {
        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;
            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) {//与搜索相关的ur
                    if (uri.getPathSegments().size() > 1) {
                        searchString = uri.getPathSegments().get(1);
                    }
                } else {
                    searchString = uri.getQueryParameter("pattern");//截取Uri链接中的参数"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) {
            c.setNotificationUri(getContext().getContentResolver(), uri);//若getContentResolver发生变化，就接收通知
        }
        return c;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {//插入一个uri，uri是一个用于标识某一互联网资源名称的字符串
        SQLiteDatabase db = mHelper.getWritableDatabase();//获得可写的数据库
        long dataId = 0, noteId = 0, insertedId = 0;
        switch (mMatcher.match(uri)) {//数据库的插入，用来存放数据
            case URI_NOTE:
                insertedId = noteId = db.insert(TABLE.NOTE, null, values);
                break;
            case URI_DATA:
                if (values.containsKey(DataColumns.NOTE_ID)) {//匹配note的ID
                    noteId = values.getAsLong(DataColumns.NOTE_ID);
                } else {
                    Log.d(TAG, "Wrong data format without note id:" + values.toString());
                }//Log用于显示，格式错误
                insertedId = dataId = db.insert(TABLE.DATA, null, values);//插入便签数据
                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);
        }

        // 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
        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 ";
                count = db.delete(TABLE.NOTE, selection, selectionArgs);
                break;
            case URI_NOTE_ITEM:
                id = uri.getPathSegments().get(1);
                /**
                 * ID that smaller than 0 is system folder which is not allowed to
                 * trash
                 */
                long noteId = Long.valueOf(id);
                if (noteId <= 0) {//ID小于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);//未知uri，则报错，显示Unknown URI
        }
        if (count > 0) {//对上述的操作进行判断，上述更改发生，count>0
            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
        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);//升级note版本
                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);//对该data的uri进行更新
                updateData = true;
                break;
            case URI_DATA_ITEM:
                id = uri.getPathSegments().get(1);//获取该项目id并将其uri更新
                count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
                        + parseSelection(selection), selectionArgs);
                updateData = true;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);// 抛出错误：未知uri
        }

        if (count > 0) {//如果发生了更改，进行通知
            if (updateData) {//data更新
                getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
            }
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    private String parseSelection(String selection) {//返回字符串规定格式
        return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
    }

    private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {//升级note的版本
        StringBuilder sql = new StringBuilder(120);//创建stringbuilder对象
        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)) {// 如果id>0且selection不为空，添加“WHERE”
            sql.append(" WHERE ");
        }
        if (id > 0) {
            sql.append(NoteColumns.ID + "=" + String.valueOf(id));
        }
        if (!TextUtils.isEmpty(selection)) {//若selection字段为空，则添加该字段
            String selectString = id > 0 ? parseSelection(selection) : selection;
            for (String args : selectionArgs) {
                selectString = selectString.replaceFirst("\\?", args);
            }
            sql.append(selectString);//增加selectString语句
        }

        mHelper.getWritableDatabase().execSQL(sql.toString());//把修改后的sql加入数据库
    }

    @Override
    public String getType(Uri uri) {//获取uri的类型
        // TODO Auto-generated method stub
        return null;//初始化，返回一个空指针
    }

}
