package net.micode.notes.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;

/**
 * 笔记应用的数据库帮助类，负责创建和管理数据库结构
 * 使用单例模式确保整个应用中只有一个数据库实例
 */
public class NotesDatabaseHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "note.db";  // 数据库名称
    private static final int DB_VERSION = 4;  // 当前数据库版本
    private static final String TAG = "NotesDatabaseHelper";  // 日志标签

    // 表名常量接口
    public interface TABLE {
        public static final String NOTE = "note";  // 笔记表
        public static final String DATA = "data";  // 数据表
    }

    // 单例实例
    private static NotesDatabaseHelper sInstance;

    // 创建笔记表的SQL语句
    private static final String CREATE_NOTE_TABLE_SQL = 
        "CREATE TABLE " + TABLE.NOTE + " (\n" +
        "    " + NoteColumns.ID + " INTEGER PRIMARY KEY,\n" +
        "    " + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000),\n" +
        "    " + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000),\n" +
        "    " + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT '',\n" +
        "    " + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1,\n" +
        "    " + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT '',\n" +
        "    " + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0\n" +
        ")";

    // 创建数据表的SQL语句
    private static final String CREATE_DATA_TABLE_SQL = 
        "CREATE TABLE " + TABLE.DATA + " (\n" +
        "    " + DataColumns.ID + " INTEGER PRIMARY KEY,\n" +
        "    " + DataColumns.MIME_TYPE + " TEXT NOT NULL,\n" +
        "    " + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0,\n" +
        "    " + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000),\n" +
        "    " + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000),\n" +
        "    " + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT '',\n" +
        "    " + DataColumns.DATA1 + " INTEGER,\n" +
        "    " + DataColumns.DATA2 + " INTEGER,\n" +
        "    " + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT '',\n" +
        "    " + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT '',\n" +
        "    " + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''\n" +
        ")";

    // 创建数据表索引的SQL语句
    private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
        "CREATE INDEX IF NOT EXISTS note_id_index ON " + TABLE.DATA + 
        "(" + DataColumns.NOTE_ID + ");";

    // 文件夹计数更新触发器
    private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
        "CREATE TRIGGER increase_folder_count_on_update " +
        "AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
        " BEGIN " +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
        "  WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
        " END";

    private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
        "CREATE TRIGGER decrease_folder_count_on_update " +
        "AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
        " BEGIN " +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
        "  WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
        "  AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
        " END";

    private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
        "CREATE TRIGGER increase_folder_count_on_insert " +
        "AFTER INSERT ON " + TABLE.NOTE +
        " BEGIN " +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
        "  WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
        " END";

    private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
        "CREATE TRIGGER decrease_folder_count_on_delete " +
        "AFTER DELETE ON " + TABLE.NOTE +
        " BEGIN " +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
        "  WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
        "  AND " + NoteColumns.NOTES_COUNT + ">0;" +
        " END";

    // 笔记内容同步触发器
    private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
        "CREATE TRIGGER update_note_content_on_insert " +
        "AFTER INSERT ON " + TABLE.DATA +
        " WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
        " BEGIN" +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
        "  WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
        " END";

    private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
        "CREATE TRIGGER update_note_content_on_update " +
        "AFTER UPDATE ON " + TABLE.DATA +
        " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
        " BEGIN" +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
        "  WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
        " END";

    private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
        "CREATE TRIGGER update_note_content_on_delete " +
        "AFTER delete ON " + TABLE.DATA +
        " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
        " BEGIN" +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.SNIPPET + "=''" +
        "  WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
        " END";

    // 级联删除触发器
    private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
        "CREATE TRIGGER delete_data_on_delete " +
        "AFTER DELETE ON " + TABLE.NOTE +
        " BEGIN" +
        "  DELETE FROM " + TABLE.DATA +
        "   WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
        " END";

    private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
        "CREATE TRIGGER folder_delete_notes_on_delete " +
        "AFTER DELETE ON " + TABLE.NOTE +
        " WHEN old." + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
        " BEGIN" +
        "  DELETE FROM " + TABLE.NOTE +
        "   WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
        " END";

    private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
        "CREATE TRIGGER folder_move_notes_on_trash " +
        "AFTER UPDATE ON " + TABLE.NOTE +
        " WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
        "  AND old." + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
        " BEGIN" +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
        "  WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
        " END";

    /**
     * 获取数据库帮助类的单例实例
     * 使用双重检查锁定确保线程安全且高效
     */
    public static synchronized NotesDatabaseHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new NotesDatabaseHelper(context.getApplicationContext());
        }
        return sInstance;
    }

    /**
     * 私有构造函数，防止外部实例化
     */
    private NotesDatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /**
     * 创建笔记表
     */
    private void createNoteTable(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_NOTE_TABLE_SQL);
            reCreateNoteTableTriggers(db);
            createSystemFolder(db);
            Log.d(TAG, "Note table created successfully");
        } catch (Exception e) {
            Log.e(TAG, "Failed to create note table: " + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 重新创建笔记表触发器
     */
    private void reCreateNoteTableTriggers(SQLiteDatabase db) {
        // 删除旧触发器
        String[] noteTriggers = {
            "increase_folder_count_on_update",
            "decrease_folder_count_on_update",
            "decrease_folder_count_on_delete",
            "delete_data_on_delete",
            "increase_folder_count_on_insert",
            "folder_delete_notes_on_delete",
            "folder_move_notes_on_trash"
        };
        
        for (String trigger : noteTriggers) {
            db.execSQL("DROP TRIGGER IF EXISTS " + trigger);
        }

        // 创建新触发器
        db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
        db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
        db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
        db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
        db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
        db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
        db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
    }

    /**
     * 创建系统文件夹
     */
    private void createSystemFolder(SQLiteDatabase db) {
        ContentValues values = new ContentValues();

        // 创建通话记录文件夹
        values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        // 创建根文件夹
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        // 创建临时文件夹
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        // 创建回收站文件夹
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);
        
        Log.d(TAG, "System folders created successfully");
    }

    /**
     * 创建数据表
     */
    private void createDataTable(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_DATA_TABLE_SQL);
            reCreateDataTableTriggers(db);
            db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
            Log.d(TAG, "Data table created successfully");
        } catch (Exception e) {
            Log.e(TAG, "Failed to create data table: " + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 重新创建数据表触发器
     */
    private void reCreateDataTableTriggers(SQLiteDatabase db) {
        // 删除旧触发器
        String[] dataTriggers = {
            "update_note_content_on_insert",
            "update_note_content_on_update",
            "update_note_content_on_delete"
        };
        
        for (String trigger : dataTriggers) {
            db.execSQL("DROP TRIGGER IF EXISTS " + trigger);
        }

        // 创建新触发器
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
    }

    /**
     * 数据库创建时调用
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "Creating database version " + DB_VERSION);
        
        // 使用事务提高性能
        db.beginTransaction();
        try {
            createNoteTable(db);
            createDataTable(db);
            db.setTransactionSuccessful();
            Log.d(TAG, "Database created successfully");
        } catch (Exception e) {
            Log.e(TAG, "Failed to create database: " + e.getMessage(), e);
            throw e;
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 数据库升级时调用
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
        
        // 使用事务确保升级过程的原子性
        db.beginTransaction();
        try {
            for (int version = oldVersion; version < newVersion; version++) {
                upgradeToVersion(db, version);
            }
            db.setTransactionSuccessful();
            Log.d(TAG, "Database upgraded successfully");
        } catch (Exception e) {
            Log.e(TAG, "Failed to upgrade database: " + e.getMessage(), e);
            throw e;
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 升级到指定版本
     */
    private void upgradeToVersion(SQLiteDatabase db, int currentVersion) {
        switch (currentVersion) {
            case 1:
                upgradeFromV1ToV2(db);
                break;
            case 2:
                upgradeFromV2ToV3(db);
                break;
            case 3:
                upgradeFromV3ToV4(db);
                break;
            default:
                throw new IllegalStateException("Unknown database version: " + currentVersion);
        }
    }

    /**
     * 从版本1升级到版本2
     */
    private void upgradeFromV1ToV2(SQLiteDatabase db) {
        Log.d(TAG, "Upgrading from version 1 to 2");
        
        // 版本1到版本2的升级包含了版本2到版本3的升级
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
        createNoteTable(db);
        createDataTable(db);
        
        Log.d(TAG, "Upgraded to version 2 successfully");
    }

    /**
     * 从版本2升级到版本3
     */
    private void upgradeFromV2ToV3(SQLiteDatabase db) {
        Log.d(TAG, "Upgrading from version 2 to 3");
        
        // 删除旧触发器
        String[] oldTriggers = {
            "update_note_modified_date_on_insert",
            "update_note_modified_date_on_delete",
            "update_note_modified_date_on_update"
        };
        
        for (String trigger : oldTriggers) {
            db.execSQL("DROP TRIGGER IF EXISTS " + trigger);
        }
        
        // 添加新列
        db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
                + " TEXT NOT NULL DEFAULT ''");
        
        // 添加回收站系统文件夹
        ContentValues values = new ContentValues();
        values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);
        
        Log.d(TAG, "Upgraded to version 3 successfully");
    }

    /**
     * 从版本3升级到版本4
     */
    private void upgradeFromV3ToV4(SQLiteDatabase db) {
        Log.d(TAG, "Upgrading from version 3 to 4");
        
        // 添加版本列
        db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
                + " INTEGER NOT NULL DEFAULT 0");
        
        Log.d(TAG, "Upgraded to version 4 successfully");
    }

    /**
     * 数据库降级时调用（如果需要）
     */
    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Downgrading database from version " + oldVersion + " to " + newVersion);
        
        // 降级策略：删除所有表并重新创建
        db.beginTransaction();
        try {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
            onCreate(db);
            db.setTransactionSuccessful();
            Log.d(TAG, "Database downgraded successfully");
        } catch (Exception e) {
            Log.e(TAG, "Failed to downgrade database: " + e.getMessage(), e);
            throw e;
        } finally {
            db.endTransaction();
        }
    }
}
