/*
 * 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.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
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.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TrashColumns;
import net.micode.notes.data.NotesDatabaseHelper;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;

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


public class DataUtils {
    public static final String TAG = "DataUtils";
    /**
     * Move notes to trash table instead of directly deleting them
     */
    public static boolean batchMoveToTrash(ContentResolver resolver, HashSet<Long> ids) {
        // 为了保持向后兼容，如果没有Context，使用旧逻辑（不备份DATA数据）
        return batchMoveToTrash(resolver, ids, null);
    }

    /**
     * Move notes to trash table instead of directly deleting them
     * @param resolver ContentResolver
     * @param ids Note IDs to move to trash
     * @param context Context (optional, needed for backing up DATA table)
     */
    public static boolean batchMoveToTrash(ContentResolver resolver, HashSet<Long> ids, Context context) {
        if (ids == null || ids.size() == 0) {
            Log.d(TAG, "the ids is null or empty");
            return true;
        }

        Cursor cursor = null;
        Cursor dataCursor = null;
        SQLiteDatabase db = null;
        try {
            // 如果提供了Context，获取数据库实例用于备份DATA数据
            if (context != null) {
                db = NotesDatabaseHelper.getInstance(context).getWritableDatabase();
            }

            for (long id : ids) {
                if(id == Notes.ID_ROOT_FOLDER || id <= 0) {
                    Log.e(TAG, "Don't move system folder root or invalid id: " + id);
                    continue;
                }

                // Query the note from note table
                cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id),
                        null, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    // Read all columns from the note
                    ContentValues trashValues = new ContentValues();

                    // Copy all columns from note to trash
                    for (String column : cursor.getColumnNames()) {
                        int columnIndex = cursor.getColumnIndex(column);
                        if (columnIndex >= 0) {
                            int type = cursor.getType(columnIndex);
                            switch (type) {
                                case Cursor.FIELD_TYPE_NULL:
                                    break;
                                case Cursor.FIELD_TYPE_INTEGER:
                                    trashValues.put(column, cursor.getLong(columnIndex));
                                    break;
                                case Cursor.FIELD_TYPE_FLOAT:
                                    trashValues.put(column, cursor.getDouble(columnIndex));
                                    break;
                                case Cursor.FIELD_TYPE_STRING:
                                    trashValues.put(column, cursor.getString(columnIndex));
                                    break;
                                case Cursor.FIELD_TYPE_BLOB:
                                    trashValues.put(column, cursor.getBlob(columnIndex));
                                    break;
                            }
                        }
                    }

                    // Set deleted_date to current time
                    trashValues.put("deleted_date", System.currentTimeMillis());

                    // Insert into trash table
                    resolver.insert(Notes.CONTENT_TRASH_URI, trashValues);

                    // 在删除note之前，先备份DATA表的数据
                    if (db != null) {
                        // 查询该note的所有DATA数据
                        dataCursor = db.query(NotesDatabaseHelper.TABLE.DATA, null,
                                DataColumns.NOTE_ID + "=?",
                                new String[]{String.valueOf(id)},
                                null, null, null);
                        
                        if (dataCursor != null && dataCursor.moveToFirst()) {
                            do {
                                // 复制DATA数据到trash_data表
                                ContentValues trashDataValues = new ContentValues();
                                for (String column : dataCursor.getColumnNames()) {
                                    int columnIndex = dataCursor.getColumnIndex(column);
                                    if (columnIndex >= 0) {
                                        int type = dataCursor.getType(columnIndex);
                                        switch (type) {
                                            case Cursor.FIELD_TYPE_NULL:
                                                break;
                                            case Cursor.FIELD_TYPE_INTEGER:
                                                trashDataValues.put(column, dataCursor.getLong(columnIndex));
                                                break;
                                            case Cursor.FIELD_TYPE_FLOAT:
                                                trashDataValues.put(column, dataCursor.getDouble(columnIndex));
                                                break;
                                            case Cursor.FIELD_TYPE_STRING:
                                                trashDataValues.put(column, dataCursor.getString(columnIndex));
                                                break;
                                            case Cursor.FIELD_TYPE_BLOB:
                                                trashDataValues.put(column, dataCursor.getBlob(columnIndex));
                                                break;
                                        }
                                    }
                                }
                                // 插入到trash_data表
                                db.insert(NotesDatabaseHelper.TABLE.TRASH_DATA, null, trashDataValues);
                            } while (dataCursor.moveToNext());
                        }
                        if (dataCursor != null) {
                            dataCursor.close();
                            dataCursor = null;
                        }
                    }
                    
                    // Delete from note table (this will trigger deletion of DATA table via trigger)
                    resolver.delete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), null, null);
                }

                if (cursor != null) {
                    cursor.close();
                    cursor = null;
                }
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, String.format("Move to trash failed: %s", e.toString()));
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (dataCursor != null) {
                dataCursor.close();
            }
        }
    }

    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
        // Instead of directly deleting, move to trash
        return batchMoveToTrash(resolver, ids, null);
    }

    public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids, Context context) {
        // Instead of directly deleting, move to trash
        return batchMoveToTrash(resolver, ids, context);
    }

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

    /**
     * Restore note from trash table back to note table
     */
    public static boolean restoreNoteFromTrash(ContentResolver resolver, long trashId) {
        // 为了保持向后兼容，如果没有Context，使用旧逻辑（不恢复DATA数据）
        return restoreNoteFromTrash(resolver, trashId, null);
    }

    /**
     * Restore note from trash table back to note table
     * @param resolver ContentResolver
     * @param trashId Trash note ID to restore
     * @param context Context (optional, needed for restoring DATA table)
     */
    public static boolean restoreNoteFromTrash(ContentResolver resolver, long trashId, Context context) {
        Cursor cursor = null;
        Cursor dataCursor = null;
        SQLiteDatabase db = null;
        try {
            // 如果提供了Context，获取数据库实例用于恢复DATA数据
            if (context != null) {
                db = NotesDatabaseHelper.getInstance(context).getWritableDatabase();
            }

            // Query the note from trash table
            cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_TRASH_URI, trashId),
                    null, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                // Read all columns from the trash note
                ContentValues noteValues = new ContentValues();
                long originalNoteId = -1;
                
                // Copy all columns from trash to note (except deleted_date)
                for (String column : cursor.getColumnNames()) {
                    if ("deleted_date".equals(column)) {
                        continue; // Skip deleted_date column
                    }
                    int columnIndex = cursor.getColumnIndex(column);
                    if (columnIndex >= 0) {
                        int type = cursor.getType(columnIndex);
                        switch (type) {
                            case Cursor.FIELD_TYPE_NULL:
                                break;
                            case Cursor.FIELD_TYPE_INTEGER:
                                long value = cursor.getLong(columnIndex);
                                noteValues.put(column, value);
                                // 保存原始note ID
                                if (NoteColumns.ID.equals(column)) {
                                    originalNoteId = value;
                                }
                                break;
                            case Cursor.FIELD_TYPE_FLOAT:
                                noteValues.put(column, cursor.getDouble(columnIndex));
                                break;
                            case Cursor.FIELD_TYPE_STRING:
                                noteValues.put(column, cursor.getString(columnIndex));
                                break;
                            case Cursor.FIELD_TYPE_BLOB:
                                noteValues.put(column, cursor.getBlob(columnIndex));
                                break;
                        }
                    }
                }

                // Insert back to note table
                Uri restoredUri = resolver.insert(Notes.CONTENT_NOTE_URI, noteValues);
                if (restoredUri == null) {
                    Log.e(TAG, "Failed to restore note to note table");
                    return false;
                }

                // 获取恢复后的note ID（可能是新的ID）
                long restoredNoteId = ContentUris.parseId(restoredUri);
                if (restoredNoteId <= 0) {
                    Log.e(TAG, "Invalid restored note ID: " + restoredNoteId);
                    return false;
                }
                
                // 恢复DATA表的数据
                if (db != null && originalNoteId > 0) {
                    // 查询trash_data表中该note的所有数据
                    dataCursor = db.query(NotesDatabaseHelper.TABLE.TRASH_DATA, null,
                            DataColumns.NOTE_ID + "=?",
                            new String[]{String.valueOf(originalNoteId)},
                            null, null, null);
                    
                    if (dataCursor != null && dataCursor.moveToFirst()) {
                        do {
                            // 复制DATA数据回data表，但使用新的note ID
                            ContentValues dataValues = new ContentValues();
                            for (String column : dataCursor.getColumnNames()) {
                                int columnIndex = dataCursor.getColumnIndex(column);
                                if (columnIndex >= 0) {
                                    int type = dataCursor.getType(columnIndex);
                                    switch (type) {
                                        case Cursor.FIELD_TYPE_NULL:
                                            break;
                                        case Cursor.FIELD_TYPE_INTEGER:
                                            long value = dataCursor.getLong(columnIndex);
                                            // 如果是NOTE_ID列，使用恢复后的note ID
                                            if (DataColumns.NOTE_ID.equals(column)) {
                                                dataValues.put(column, restoredNoteId);
                                            } else {
                                                dataValues.put(column, value);
                                            }
                                            break;
                                        case Cursor.FIELD_TYPE_FLOAT:
                                            dataValues.put(column, dataCursor.getDouble(columnIndex));
                                            break;
                                        case Cursor.FIELD_TYPE_STRING:
                                            dataValues.put(column, dataCursor.getString(columnIndex));
                                            break;
                                        case Cursor.FIELD_TYPE_BLOB:
                                            dataValues.put(column, dataCursor.getBlob(columnIndex));
                                            break;
                                    }
                                }
                            }
                            // 插入到data表
                            db.insert(NotesDatabaseHelper.TABLE.DATA, null, dataValues);
                        } while (dataCursor.moveToNext());
                        
                        // 删除trash_data表中的数据
                        db.delete(NotesDatabaseHelper.TABLE.TRASH_DATA,
                                DataColumns.NOTE_ID + "=?",
                                new String[]{String.valueOf(originalNoteId)});
                    }
                    if (dataCursor != null) {
                        dataCursor.close();
                        dataCursor = null;
                    }
                }
                
                // Delete from trash table
                resolver.delete(ContentUris.withAppendedId(Notes.CONTENT_TRASH_URI, trashId), null, null);

                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, String.format("Restore from trash failed: %s", e.toString()));
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (dataCursor != null) {
                dataCursor.close();
            }
        }
    }

    /**
     * Permanently delete note from trash table
     */
    public static boolean permanentlyDeleteFromTrash(ContentResolver resolver, long trashId) {
        return permanentlyDeleteFromTrash(resolver, trashId, null);
    }

    /**
     * Permanently delete note from trash table
     * @param resolver ContentResolver
     * @param trashId Trash note ID to permanently delete
     * @param context Context (optional, needed for deleting trash_data table)
     */
    public static boolean permanentlyDeleteFromTrash(ContentResolver resolver, long trashId, Context context) {
        try {
            // 如果提供了Context，先删除trash_data表中的数据
            if (context != null) {
                SQLiteDatabase db = NotesDatabaseHelper.getInstance(context).getWritableDatabase();
                db.delete(NotesDatabaseHelper.TABLE.TRASH_DATA,
                        DataColumns.NOTE_ID + "=?",
                        new String[]{String.valueOf(trashId)});
            }
            
            int count = resolver.delete(ContentUris.withAppendedId(Notes.CONTENT_TRASH_URI, trashId), null, null);
            return count > 0;
        } catch (Exception e) {
            Log.e(TAG, String.format("Permanently delete from trash failed: %s", e.toString()));
            return false;
        }
    }

    /**
     * Clear all notes from trash table
     */
    public static boolean clearAllTrash(ContentResolver resolver) {
        return clearAllTrash(resolver, null);
    }

    /**
     * Clear all notes from trash table
     * @param resolver ContentResolver
     * @param context Context (optional, needed for clearing trash_data table)
     */
    public static boolean clearAllTrash(ContentResolver resolver, Context context) {
        try {
            // 如果提供了Context，先清空trash_data表
            if (context != null) {
                SQLiteDatabase db = NotesDatabaseHelper.getInstance(context).getWritableDatabase();
                db.delete(NotesDatabaseHelper.TABLE.TRASH_DATA, null, null);
            }
            
            int count = resolver.delete(Notes.CONTENT_TRASH_URI, null, null);
            Log.d(TAG, "Cleared " + count + " notes from trash");
            // Return true even if count is 0, as it might mean the trash was already empty
            return true;
        } catch (Exception e) {
            Log.e(TAG, String.format("Clear all trash failed: %s", e.toString()));
            return false;
        }
    }

    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();
            // 替换[IMAGE]标签为友好的占位符
            snippet = snippet.replaceAll("\\[IMAGE\\].*?\\[/IMAGE\\]", "[图片]");
            int index = snippet.indexOf('\n');
            if (index != -1) {
                snippet = snippet.substring(0, index);
            }
        }
        return snippet;
    }
}
