/*
 * 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 net.micode.notes.ui.ApplicationContexts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.File;

public class DataUtils {
    public static final String TAG = "DataUtils";
    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
        return batchDeleteNotes(resolver, ids, true);
    }

    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids, boolean deleteImage) {
        if (ids == null) {
            return true;
        }

        // 获取要删除的笔记内容中的图片文件名
        if (deleteImage) {
            Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, new String[] {
                    Notes.NoteColumns.ID, Notes.NoteColumns.SNIPPET
            }, NoteColumns.ID + " in (" + DataUtils.formatLongIds(ids) + ")", null, null);
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    long id = cursor.getLong(0);
                    String content = cursor.getString(1);
                    if (content != null && content.contains("[图片:")) {
                        try {
                            // 提取并删除图片文件
                            String[] imageNames = ImageTool.extractImagesFromText(content);
                            if (imageNames != null) {
                                for (String imageName : imageNames) {
                                    File imageFile = new File(ResourceParser.getNotesImageDir(ApplicationContexts.getApplication()), imageName);
                                    if (imageFile.exists()) {
                                        imageFile.delete();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Error deleting note images", e);
                        }
                    }
                }
                cursor.close();
            }
        }
        
        // 删除笔记
        StringBuilder sb = new StringBuilder();
        for (Long id : ids) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(id.toString());
        }

        int result = resolver.delete(Notes.CONTENT_NOTE_URI,
                NoteColumns.ID + " in (" + sb.toString() + ")", null);
        return result > 0;
    }

    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);
        resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
    }

    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) {
            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());
        }

        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}}
     */
    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);

        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),
                null,
                NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
                new String [] {String.valueOf(type)},
                null);

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

    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;
    }

    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;
    }

    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) {
        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);

        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);
                        widget.widgetType = c.getInt(1);
                        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) {
        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) {
        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);

        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;
    }

    public static String getSnippetById(ContentResolver resolver, long noteId) {
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
                new String [] { NoteColumns.SNIPPET },
                NoteColumns.ID + "=?",
                new String [] { String.valueOf(noteId)},
                null);

        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);
    }

    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;
    }

    /**
     * 将笔记标记为已删除状态，移入回收站
     * @param resolver ContentResolver
     * @param ids 待删除的笔记ID集合
     * @return 操作是否成功
     */
    public static boolean batchMoveToTrash(ContentResolver resolver, HashSet<Long> ids) {
        if (ids == null || ids.size() == 0) {
            Log.d(TAG, "No ids to move to trash");
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
        long currentTime = System.currentTimeMillis();
        
        // 先查询每个笔记的原始文件夹ID
        for (long id : ids) {
            if(id == Notes.ID_ROOT_FOLDER || id < 0) {
                Log.e(TAG, "Don't move system folder or note to trash");
                continue;
            }
            
            // 查询原始文件夹ID
            Cursor cursor = resolver.query(
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id),
                new String[] { NoteColumns.PARENT_ID },
                null, null, null);
            
            long originalParentId = Notes.ID_ROOT_FOLDER; // 默认为根文件夹
            
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    originalParentId = cursor.getLong(0);
                }
                cursor.close();
            }
            
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            
            // 记录原始文件夹ID
            builder.withValue(NoteColumns.ORIGIN_PARENT_ID, originalParentId);
            builder.withValue(NoteColumns.PARENT_ID, Notes.ID_TRASH_FOLER);
            builder.withValue(NoteColumns.STATUS, Notes.NOTE_STATUS_DELETED);
            builder.withValue(NoteColumns.DELETE_DATE, currentTime);
            operationList.add(builder.build());
        }

        try {
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
            if (results == null || results.length == 0 || results[0] == null) {
                Log.d(TAG, "Move notes to trash 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 ContentResolver
     * @param ids 待恢复的笔记ID集合
     * @return 操作是否成功
     */
    public static boolean batchRestoreFromTrash(ContentResolver resolver, HashSet<Long> ids) {
        if (ids == null || ids.size() == 0) {
            Log.d(TAG, "No ids to restore from trash");
            return true;
        }

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
        
        for (long id : ids) {
            // 查询原始文件夹ID
            Cursor cursor = resolver.query(
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id),
                new String[] { NoteColumns.ORIGIN_PARENT_ID },
                null, null, null);
            
            long originalParentId = Notes.ID_ROOT_FOLDER; // 默认为根文件夹
            
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    originalParentId = cursor.getLong(0);
                    // 确保文件夹存在
                    if (originalParentId != Notes.ID_ROOT_FOLDER && !existInNoteDatabase(resolver, originalParentId)) {
                        originalParentId = Notes.ID_ROOT_FOLDER;
                    }
                }
                cursor.close();
            }
            
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
            builder.withValue(NoteColumns.PARENT_ID, originalParentId);
            builder.withValue(NoteColumns.STATUS, Notes.NOTE_STATUS_NORMAL);
            builder.withValue(NoteColumns.DELETE_DATE, 0);
            operationList.add(builder.build());
        }

        try {
            ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
            if (results == null || results.length == 0 || results[0] == null) {
                Log.d(TAG, "Restore notes from trash 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 ContentResolver
     * @param ids 待删除的笔记ID集合
     * @return 操作是否成功
     */
    public static boolean batchPermanentlyDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
        return batchDeleteNotes(resolver, ids);
    }

    /**
     * 设置回收站自动清理时间间隔
     * @param context Context
     * @param days 天数
     * @return 操作是否成功
     */
    public static boolean setTrashCleanInterval(Context context, int days) {
        if (days <= 0) {
            Log.e(TAG, "Invalid trash clean interval days: " + days);
            return false;
        }
        
        SharedPreferences sp = context.getSharedPreferences(
                "trash_settings", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("clean_interval_days", days);
        editor.putLong("last_setting_time", System.currentTimeMillis());
        return editor.commit();
    }

    /**
     * 获取回收站自动清理时间间隔
     * @param context Context
     * @return 天数
     */
    public static int getTrashCleanInterval(Context context) {
        SharedPreferences sp = context.getSharedPreferences(
                "trash_settings", Context.MODE_PRIVATE);
        return sp.getInt("clean_interval_days", Notes.DEFAULT_CLEAN_DAYS);
    }

    /**
     * 清理过期的回收站笔记
     * @param context Context
     * @return 删除的数量
     */
    public static int cleanExpiredTrashNotes(Context context) {
        ContentResolver resolver = context.getContentResolver();
        int cleanDays = getTrashCleanInterval(context);
        long expireTime = System.currentTimeMillis() - cleanDays * 86400000L;
        
        // 查找过期的笔记
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, 
                new String[] { NoteColumns.ID },
                NoteColumns.STATUS + "=" + Notes.NOTE_STATUS_DELETED + " AND " +
                NoteColumns.DELETE_DATE + "<" + expireTime, 
                null, null);
        
        if (cursor == null) {
            return 0;
        }
        
        HashSet<Long> expiredIds = new HashSet<Long>();
        try {
            while (cursor.moveToNext()) {
                expiredIds.add(cursor.getLong(0));
            }
        } finally {
            cursor.close();
        }
        
        int count = expiredIds.size();
        if (count > 0) {
            batchPermanentlyDeleteNotes(resolver, expiredIds);
            // 记录清理日志
            logTrashCleanup(context, count, expireTime);
        }
        
        return count;
    }
    
    /**
     * 检查回收站是否已达到上限
     * @param resolver ContentResolver
     * @return 是否已达上限
     */
    public static boolean isTrashFull(ContentResolver resolver) {
        Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, 
                new String[] { "COUNT(*)" },
                NoteColumns.STATUS + "=" + Notes.NOTE_STATUS_DELETED, 
                null, null);
        
        if (cursor == null) {
            return false;
        }
        
        int count = 0;
        try {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } finally {
            cursor.close();
        }
        
        return count >= Notes.TRASH_LIMIT_COUNT;
    }
    
    /**
     * 记录回收站清理日志
     * @param context Context
     * @param count 清理数量
     * @param expireTime 过期时间
     */
    private static void logTrashCleanup(Context context, int count, long expireTime) {
        SharedPreferences sp = context.getSharedPreferences(
                "trash_logs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        
        // 使用时间戳作为键
        String key = String.valueOf(System.currentTimeMillis());
        JSONObject log = new JSONObject();
        try {
            log.put("count", count);
            log.put("time", System.currentTimeMillis());
            log.put("expire_time", expireTime);
            editor.putString(key, log.toString());
            
            // 限制日志数量，仅保留最近7条
            Set<String> keys = new HashSet<String>(sp.getAll().keySet());
            if (keys.size() > 7) {
                List<String> keyList = new ArrayList<String>(keys);
                Collections.sort(keyList);
                for (int i = 0; i < keyList.size() - 7; i++) {
                    editor.remove(keyList.get(i));
                }
            }
            
            editor.commit();
        } catch (JSONException e) {
            Log.e(TAG, "Failed to create trash cleanup log: " + e.getMessage());
        }
    }

    /**
     * 将HashSet中的长整型ID格式化为SQL IN语句的字符串
     */
    public static String formatLongIds(HashSet<Long> ids) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Long id : ids) {
            if (first) {
                first = false;
            } else {
                sb.append(",");
            }
            sb.append(id);
        }
        return sb.toString();
    }
}
