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

//使用的包
import android.content.ContentProviderOperation;
// 导入相关的库
import android.content.ContentProviderResult;
//批量删除笔记
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;

import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
//便签栏的数据
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;

import java.util.ArrayList;
import java.util.HashSet;

public class DataUtils {
    // 数据的集成工具类
    public static final String TAG = "DataUtils";

    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { // 直接删除多个笔记
        // 这是一个处理批量删除便签的方法
        if (ids == null) {
            Log.d(TAG, "the ids is null");
            // Android Logcat使用起来可以方便的观察调试内容
            return true;
        }
        if (ids.size() == 0) {
            Log.d(TAG, "no id is in the hashset");
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); // 提供一个任务列表
        for (long id : ids) {
            if (id == Notes.ID_ROOT_FOLDER) {
                Log.e(TAG, "Don't delete system folder root");
                continue;
            } // 如果发现是根文件夹，则不删除
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); // 用newDelete实现删除功能
            operationList.add(builder.build()); //
        }
        try {
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);// 主机名（或叫Authority）用于唯一标识这个ContentProvider，外部调用者可以根据这个标识来找到它。
            // 数据库事务，数据库事务是由一组数据库操作序列组成，事务作为一个整体被执行
            if (results == null || results.length == 0 || results[0] == null) {
                Log.d(TAG, "delete notes failed, ids:" + ids.toString());
                // 检测当前要删除的便签是否是根目录，如果是根目录，，返回异常信息
                return false;
            }
            return true;
        } catch (RemoteException e) {
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
            // 函数：String.format(Locale locale, String format, Object… args)
            // 使用指定的语言环境，制定字符串格式和参数生成格式化的字符串。
        } catch (OperationApplicationException e) {
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
        }
        return false;
    }

    public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
        // 将笔记移动至文件夹
        ContentValues values = new ContentValues();// 将PARENT_ID更改为目标目录ID
        values.put(NoteColumns.PARENT_ID, desFolderId);
        values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
        values.put(NoteColumns.LOCAL_MODIFIED, 1);
        resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); // 对需要移动的便签进行数据更新，然后用update实现
    }

    public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
            // 批量移动
            long folderId) {
        // ID为空的情况
        if (ids == null) {
            Log.d(TAG, "the ids is null");
            // ID为空的情况
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
        for (long id : ids) {
            // 为uri加上id
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); // 通过withAppendedId方法，为该Uri加上ID
            builder.withValue(NoteColumns.PARENT_ID, folderId);
            // 代码块：以下两句话和上面一个方法类似，就是修改便签的父节点id为新的文件夹的id，然后更改修改标志
            builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
            // 更改状态置为1
            operationList.add(builder.build());
        } // 将ids里包含的每一列的数据逐次加入到operationList中，等待最后的批量处理

        try {
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); // applyBatch一次性处理一个操作列表
            // 调用applybatch一次性处理一个操作列表
            if (results == null || results.length == 0 || results[0] == null) {
                Log.d(TAG, "delete notes failed, ids:" + ids.toString());
                return false;
            }
            return true;
        } catch (RemoteException e) {
            // . 确定格式
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
        } catch (OperationApplicationException e) {
            Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
        }
        return false;
    }

    /**
     * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
     */
    public static int getUserFolderCount(ContentResolver resolver) {
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
                new String[] { "COUNT(*)" },
                NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
                new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) },
                null); // 筛选条件：源文件不为trash folder

        int count = 0;
        if (cursor != null) {
            // 语句块：尝试得到用户文件夹的数量
            if (cursor.moveToFirst()) {
                try {
                    // .异常处理
                    count = cursor.getInt(0);
                } catch (IndexOutOfBoundsException e) {
                    Log.e(TAG, "get folder count failed:" + e.toString());
                } finally {
                    cursor.close();
                }
            }
        }
        return count;
    }

    public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
        // 在数据库中是否可见
        Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), // 通过withAppendedId方法，为该Uri加上ID
                null,
                NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
                new String[] { String.valueOf(type) },
                null); // 查询条件：type符合，且不属于垃圾文件夹

        boolean exist = false;
        if (cursor != null) {
            if (cursor.getCount() > 0) {// 用getcount函数判断cursor是否为空
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }

    public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
        // 判断该note是否在数据库中存在
        Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
                null, null, null, null);

        boolean exist = false;
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }

    public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
        // 检查文件名字是否可见
        Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
                null, null, null, null);
        // 通过URI与dataId在数据库中查找数据
        boolean exist = false;
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                // 调用对应的uri的数据值进行查询
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }

    public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
        // 函数：通过名字查询文件是否存在
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
                // 语句：筛选类型正确的、未被删除的和名字对应得上的
                NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
                        " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
                        " AND " + NoteColumns.SNIPPET + "=?",
                new String[] { name }, null);
        // 通过名字查询文件是否存在
        boolean exist = false;
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }

    public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
        // 使用hashset来存储不同窗口的id和type并且建立对应关系
        Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
                new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
                NoteColumns.PARENT_ID + "=?",
                new String[] { String.valueOf(folderId) },
                null); // 查询条件：父ID是传入的folderId;

        HashSet<AppWidgetAttribute> set = null;
        if (c != null) {
            // 语句块：将app窗口的属性加入到HashSet中
            if (c.moveToFirst()) {
                set = new HashSet<AppWidgetAttribute>();
                do {
                    try {
                        AppWidgetAttribute widget = new AppWidgetAttribute();
                        widget.widgetId = c.getInt(0); // 0对应的NoteColumns.WIDGET_ID
                        widget.widgetType = c.getInt(1); // 1对应的NoteColumns.WIDGET_TYPE
                        set.add(widget);
                    } catch (IndexOutOfBoundsException e) {
                        Log.e(TAG, e.toString());
                    }
                } while (c.moveToNext()); // 查询下一条
            }
            c.close();
        }
        return set;
    }

    public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
        // 通过笔记ID获取号码
        Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
                new String[] { CallNote.PHONE_NUMBER },
                CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
                new String[] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
                null);// 新建字符列表

        if (cursor != null && cursor.moveToFirst()) {
            // 语句块： 获取电话号码，并处理异常。
            try {
                return cursor.getString(0);
            } catch (IndexOutOfBoundsException e) {
                Log.e(TAG, "Get call number fails " + e.toString());
            } finally {
                cursor.close();
            }
        }
        return "";
    }

    public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
        // 同样的，通过映射关系，通过号码和日期获取ID
        Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
                new String[] { CallNote.NOTE_ID },
                CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
                        + CallNote.PHONE_NUMBER + ",?)",
                new String[] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
                null);
        // 通过数据库操作，查询条件是（callDate和phoneNumber匹配传入参数的值）

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                try {
                    return cursor.getLong(0); // 0对应的CallNote.NOTE_ID
                } catch (IndexOutOfBoundsException e) {
                    Log.e(TAG, "Get call note id fails " + e.toString());
                }
            }
            cursor.close();
        }
        return 0;
    }

    public static String getSnippetById(ContentResolver resolver, long noteId) {
        // 按ID获取片段
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
                new String[] { NoteColumns.SNIPPET },
                NoteColumns.ID + "=?",
                new String[] { String.valueOf(noteId) },
                null);// 查询条件：noteId

        if (cursor != null) {
            String snippet = "";
            if (cursor.moveToFirst()) {
                snippet = cursor.getString(0);
            }
            cursor.close();
            return snippet;
        }
        throw new IllegalArgumentException("Note is not found with id: " + noteId);
        //1. IllegalArgumentException是非法传参异常，也就是参数传的类型冲突，属于RunTimeException运行时异常
    }

    public static String getFormattedSnippet(String snippet) { // 对字符串进行格式处理，将字符串两头的空格去掉，同时将换行符去掉
        // 按ID获取片段
        if (snippet != null) {
            snippet = snippet.trim();
            int index = snippet.indexOf('\n');
            if (index != -1) {
                snippet = snippet.substring(0, index);
            }
        }
        return snippet;
    }

}