/*
 * 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");
            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"); //检测当前id是不是指向根目录，若是返回一个异常信息
                continue; //如果发现是根文件夹，则不删除
            }
            ContentProviderOperation.Builder builder = ContentProviderOperation //使用newdelete进行删除
                    .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            operationList.add(builder.build()); //将操作添加至列表
        } 
        try { //返回被删除的数据，如果返回为空则删除失败返回false，打印异常信息，删除成功返回true
            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()));
        } 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(); //实例化一个contentValues类
        values.put(NoteColumns.PARENT_ID, desFolderId); //将当前ID更改为移动的目录ID
        values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); //设置origin也即原本的父节点为原本的文件夹的id
        values.put(NoteColumns.LOCAL_MODIFIED, 1); //是否修改状态置为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) {
        if (ids == null) { // 判断便签ID是否为空
            Log.d(TAG, "the ids is null");
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); //将ids里包含的每一列的数据逐次加入到operationList中，等待最后的批量处理
        for (long id : ids) {  //遍历所有选中的便签的id
            ContentProviderOperation.Builder builder = ContentProviderOperation //通过withAppendedId方法，为该Uri加上ID
                    .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            builder.withValue(NoteColumns.PARENT_ID, folderId); //修改便签的父节点ID为新的文件夹的ID
            builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 更改状态置为1
            operationList.add(builder.build()); //将移动的操作添加到操作列表
        }

        try { //对异常进行处理与汇报的容错机制
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); //使用函数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)}, //String.valueof将形参转成字符串返回
                null);

        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, // sql语句，表示筛选出列中type等于string数组中type，且每一项的PARENT_ID不等于Notes.ID.TRAXH_FOLDER
                new String [] {String.valueOf(type)},
                null); // 查询条件：type符合，且不属于垃圾文件夹

        boolean exist = false; //判断note是否在数据库中，并返回相应的布尔值
        if (cursor != null) { //用getcount函数判断cursor是否为空
            if (cursor.getCount() > 0) {
                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) { //根据getcount此时的值可以判断dataID的存在性
            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), //通过URI与dataId在数据库中查找数据
                null, null, null, null);

        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, //筛选出type相同，并且未被删除，名字对的上的
                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) { //判断找到的文件名返回文件是否存在的bool值
            if(cursor.getCount() > 0) {
                exist = true;
            }
            cursor.close();
        }
        return exist;
    }

    public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { //获取便签的小部件
        Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, //查询条件:父id为传入的文件夹id
                new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
                NoteColumns.PARENT_ID + "=?",
                new String[] { String.valueOf(folderId) },
                null);

        HashSet<AppWidgetAttribute> set = null; //根据窗口的记录一一添加对应的属性值
        if (c != null) { //如果为null，说明该文件夹没有窗口，直接返回空即可
            if (c.moveToFirst()) {
                set = new HashSet<AppWidgetAttribute>();
                do {
                    try { //把每一个条目对应的窗口id和type记录下来，放到set里面。每一行的第0个int和第1个int分别对应widgetId和widgetType
                        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, //通过数据库操作，查询条件是（callDate和phoneNumber匹配传入参数的值）
                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);

        if (cursor != null) { //得到该note的系统属性，并以Long值的形式来保存
            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, //通过ID查询
                new String [] { NoteColumns.SNIPPET },
                NoteColumns.ID + "=?",
                new String [] { String.valueOf(noteId)},
                null); //通过数据库操作，查询条件是（callDate和phoneNumber匹配传入参数的值

        if (cursor != null) { //以string的形式获取该对象当前行指定列的值
            String snippet = ""; //对字符串进行格式处理，将字符串两头的空格去掉同时将换行符去掉
            if (cursor.moveToFirst()) {
                snippet = cursor.getString(0);
            }
            cursor.close();
            return snippet;
        }
        throw new IllegalArgumentException("Note is not found with id: " + noteId); //IllegalArgumentException即非法传参异常，传的参数类型冲突
    }

    public static String getFormattedSnippet(String snippet) { //把文件名标准化
        if (snippet != null) {
            snippet = snippet.trim(); //trim()函数: 移除字符串两侧的空白字符或其他预定义字符
            int index = snippet.indexOf('\n');
            if (index != -1) {
                snippet = snippet.substring(0, index); //截取到第一个换行符
            }
        }
        return snippet;
    }
}
