/*
 * 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"; // 日志标签
    /**
     批量删除给定 ids 的便签
     @param resolver 内容解析器
     @param ids 要删除的便签 id 集合
     @return 如果删除成功则返回 true，否则返回 false
     */
    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
        // 检查 ids 是否为 null
        if (ids == null) {
            Log.d(TAG, "the ids is null");
            return true;
        }
        // 检查 ids 集合是否为空
        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;
            }
            // 创建一个删除操作以删除指定 id 的便签
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            operationList.add(builder.build());
        }
        try {
            // 应用批量删除操作
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
            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;
    }
    /**
     将便签移动到指定文件夹
     @param resolver 内容解析器
     @param id 要移动的便签 id
     @param srcFolderId 原文件夹 id
     @param desFolderId 目标文件夹 id
     */
    public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
        ContentValues values = new ContentValues();
        values.put(NoteColumns.PARENT_ID, desFolderId);
        values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
        values.put(NoteColumns.LOCAL_MODIFIED, 1);
        //对需要移动的便签进行数据更新，然后用update实现
        resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
    }
    /**
    批量移动便签到指定文件夹
    @param resolver 内容解析器
    @param ids 要移动的便签 id 集合
    @param folderId 目标文件夹 id
    @return 如果移动成功则返回 true，否则返回 false
     */
    public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
            long folderId) {
        if (ids == null) {
            Log.d(TAG, "the ids is null");
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
        for (long id : ids) {
            //通过withAppendedId方法，为该Uri加上ID
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            builder.withValue(NoteColumns.PARENT_ID, folderId);
            builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
            operationList.add(builder.build());
        }//将ids里包含的每一列的数据逐次加入到operationList中，等待最后的批量处理

        try {
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
            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}}
     */
    /**
    获取用户文件夹的数量（不包括系统文件夹 {@link Notes#TYPE_SYSTEM}）
    @param resolver 内容解析器
    @return 用户文件夹的数量
     */
    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;
    }
    /**
     检查便签是否在数据库中可见
     @param resolver 内容解析器
     @param noteId 便签 id
     @param type 便签类型
     @return 如果便签可见则返回 true，否则返回 false
     */
    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;
    }
    /**
     检查便签是否存在于便签数据库中
     @param resolver 内容解析器
     @param noteId 便签 id
     @return 如果便签存在则返回 true，否则返回 false
     */
    public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
        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;
    }
    /**
     检查数据是否存在于数据数据库中
     @param resolver 内容解析器
     @param dataId 数据 id
     @return 如果数据存在则返回 true，否则返回 false
     */
    public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
        Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
                null, null, null, null);

        boolean exist = false;
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }
    /**
     检查文件夹名称是否可见
     @param resolver 内容解析器
     @param name 文件夹名称
     @return 如果文件夹名称可见则返回 true，否则返回 false
     */
    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;
    }
    /**
     获取文件夹内的小部件信息
     @param resolver 内容解析器
     @param folderId 文件夹 id
     @return 包含小部件信息的 HashSet
     */
    public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
        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) {
            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;
    }
    /**
     根据便签 id获取通话号码
     @param resolver 内容解析器
     @param noteId 便签 id
     @return 通话号码
     */
    public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
        // 通过ContentResolver查询Notes.CONTENT_DATA_URI，获取CallNote.NOTE_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 "";
    }
    /**
     * 根据电话号码和通话日期获取便签 ID
     * @param resolver 内容解析器
     * @param phoneNumber 电话号码
     * @param callDate 通话日期
     * @return 便签 ID
     */
    public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
        // 通过ContentResolver查询Notes.CONTENT_DATA_URI，获取CallNote.NOTE_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);
                } catch (IndexOutOfBoundsException e) {
                    Log.e(TAG, "Get call note id fails " + e.toString());
                }
            }
            cursor.close();
        }
        return 0; // 如果未找到匹配的Note ID，则返回0
    }
    /**
     * 根据便签 ID获取摘要信息
     * @param resolver 内容解析器
     * @param noteId 便签 ID
     * @return 摘要信息
     * @throws IllegalArgumentException 如果未找到对应的便签，则抛出异常
     */
    public static String getSnippetById(ContentResolver resolver, long noteId) {
        // 通过ContentResolver查询Notes.CONTENT_NOTE_URI，获取NoteColumns.SNIPPET
        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); // 获取查询到的Snippet
            }
            cursor.close();
            return snippet; // 返回Snippet
        }
        throw new IllegalArgumentException("Note is not found with id: " + noteId); // 如果未找到对应的Note，则抛出异常
    }
    /**
     * 格式化摘要信息
     * @param snippet 摘要信息
     * @return 格式化后的摘要信息
     */
    public static String getFormattedSnippet(String snippet) {
        if (snippet != null) {
            snippet = snippet.trim(); // 去除首尾空格
            int index = snippet.indexOf('\n'); // 查找换行符的位置
            if (index != -1) {
                snippet = snippet.substring(0, index); // 截取换行符之前的部分
            }
        }
        return snippet; // 返回处理后的Snippet
    }
}
