/*
 * 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.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;

    // 表名接口
    public interface TABLE {
        public static final String NOTE = "note"; // 笔记表

        public static final String DATA = "data"; // 数据表
    }

    // 日志标签
    private static final String TAG = "NotesDatabaseHelper";

    // 单例实例
    private static NotesDatabaseHelper mInstance;

    // 创建笔记表的SQL语句
    private static final String CREATE_NOTE_TABLE_SQL =
        "CREATE TABLE " + TABLE.NOTE + "(" +
            NoteColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
            NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父ID
            NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期
            NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景颜色ID
            NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
            NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件
            NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
            NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量
            NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 笔记摘要
            NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型
            NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 小部件ID
            NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
            NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID
            NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标志
            NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父ID
            NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID
            NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号
        ")";

    // 创建数据表的SQL语句
    private static final String CREATE_DATA_TABLE_SQL =
        "CREATE TABLE " + TABLE.DATA + "(" +
            DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
            DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型
            DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 笔记ID
            NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
            NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
            DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容
            DataColumns.DATA1 + " INTEGER," + // 数据1
            DataColumns.DATA2 + " INTEGER," + // 数据2
            DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 数据3
            DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 数据4
            DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 数据5
        ")";

    // 创建数据表NOTE_ID索引的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 + ");";

    /**
     * Increase folder's note count when move note to the folder
     */
    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";

    /**
     * Decrease folder's note count when move note from folder
     */
    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";

    /**
     * Increase folder's note count when insert new note to the folder
     */
    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";

    /**
     * Decrease folder's note count when delete note from the folder
     */
    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";

    /**
     * Update note's content when insert data with type {@link DataConstants#NOTE}
     */
    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";

    /**
     * Update note's content when data with {@link DataConstants#NOTE} type has changed
     */
    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";

    /**
     * Update note's content when data with {@link DataConstants#NOTE} type has deleted
     */
    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";

    /**
     * Delete datas belong to note which has been deleted
     */
    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";

    /**
     * Delete notes belong to folder which has been deleted
     */
    private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
        "CREATE TRIGGER folder_delete_notes_on_delete " +
        " AFTER DELETE ON " + TABLE.NOTE +
        " BEGIN" +
        "  DELETE FROM " + TABLE.NOTE +
        "   WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
        " END";

    /**
     * Move notes belong to folder which has been moved to trash folder
     */
    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 +
        " BEGIN" +
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
        "  WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
        " END";

    // 构造函数，用于创建 NotesDatabaseHelper 对象
    public NotesDatabaseHelper(Context context) {
        // 调用父类 SQLiteOpenHelper 的构造函数
        // 参数 context：上下文对象，用于定位数据库文件的位置
        // 参数 DB_NAME：数据库的名称，用于创建或打开数据库
        // 参数 null：游标工厂，通常为 null，表示使用默认游标
        // 参数 DB_VERSION：数据库版本号，用于管理数据库的升级
        super(context, DB_NAME, null, DB_VERSION);
    }

    // 定义一个方法，用于创建笔记表
    public void createNoteTable(SQLiteDatabase db) {
        // 执行SQL语句，创建笔记表
        db.execSQL(CREATE_NOTE_TABLE_SQL);
        // 重新创建笔记表的触发器
        reCreateNoteTableTriggers(db);
        // 创建系统文件夹
        createSystemFolder(db);
        // 使用Log.d输出调试信息，表示笔记表已创建
        Log.d(TAG, "note table has been created");
    }

    // 定义一个私有方法，用于重新创建笔记表触发器
    private void reCreateNoteTableTriggers(SQLiteDatabase db) {
        // 删除名为 "increase_folder_count_on_update" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
        // 删除名为 "decrease_folder_count_on_update" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
        db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
        db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
        // 删除名为 "delete_data_on_delete" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
        db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
        db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");

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

    /**
     * 创建系统文件夹的方法
     * @param db SQLiteDatabase对象，用于操作数据库
     */
    private void createSystemFolder(SQLiteDatabase db) {
        // 创建一个ContentValues对象，用于存储要插入的数据
        ContentValues values = new ContentValues();

        /**
         * call record foler for call notes
         */
        values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        /**
         * root folder which is default folder
         */
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        /**
         * temporary folder which is used for moving note
         */
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);

        /**
         * create trash folder
         */
        values.clear();
        values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
        db.insert(TABLE.NOTE, null, values);
    }

    // 定义一个方法，用于创建数据表
    public void createDataTable(SQLiteDatabase db) {
        // 执行SQL语句，创建数据表
        db.execSQL(CREATE_DATA_TABLE_SQL);
        // 重新创建数据表触发器
        reCreateDataTableTriggers(db);
        db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
        Log.d(TAG, "data table has been created");
    }

    // 定义一个私有方法，用于重新创建数据表触发器
    private void reCreateDataTableTriggers(SQLiteDatabase db) {
        // 删除名为 "update_note_content_on_insert" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
        // 删除名为 "update_note_content_on_update" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
        // 删除名为 "update_note_content_on_delete" 的触发器，如果存在的话
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");

        // 创建名为 "DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER" 的触发器
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
        // 创建名为 "DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER" 的触发器
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
        // 创建名为 "DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER" 的触发器
        db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
    }

    static synchronized NotesDatabaseHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new NotesDatabaseHelper(context);
        }
        return mInstance;
    }

    @Override
    // 重写父类或接口中的onCreate方法，用于在数据库创建时执行初始化操作
    public void onCreate(SQLiteDatabase db) {
        // 调用createNoteTable方法，创建笔记表
        createNoteTable(db);
        // 调用createDataTable方法，创建数据表
        createDataTable(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 初始化标志变量，用于决定是否需要重新创建触发器
        boolean reCreateTriggers = false;
        // 初始化标志变量，用于跳过版本2的升级
        boolean skipV2 = false;

        // 如果旧版本是1，则升级到版本2
        if (oldVersion == 1) {
            upgradeToV2(db); // 调用升级到版本2的方法
            skipV2 = true; // this upgrade including the upgrade from v2 to v3
            oldVersion++;
        }

        if (oldVersion == 2 && !skipV2) {
            upgradeToV3(db);
            reCreateTriggers = true;
            oldVersion++;
        }

        if (oldVersion == 3) {
            upgradeToV4(db);
            oldVersion++;
        }

        if (reCreateTriggers) {
            reCreateNoteTableTriggers(db);
            reCreateDataTableTriggers(db);
        }

        if (oldVersion != newVersion) {
            throw new IllegalStateException("Upgrade notes database to version " + newVersion
                    + "fails");
        }
    }

    private void upgradeToV2(SQLiteDatabase db) {
        // 删除名为TABLE.NOTE的表，如果该表存在
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
        // 删除名为TABLE.DATA的表，如果该表存在
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
        // 调用createNoteTable方法，创建新的NOTE表
        createNoteTable(db);
        // 调用createDataTable方法，创建新的DATA表
        createDataTable(db);
    }

    private void upgradeToV3(SQLiteDatabase db) {
        // drop unused triggers
        db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
        db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
        db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
        // add a column for gtask id
        db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
                + " TEXT NOT NULL DEFAULT ''");
        // add a trash system folder
        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);
    }

    // 定义一个私有方法，用于将数据库升级到版本4
    private void upgradeToV4(SQLiteDatabase db) {
        // 执行一条SQL语句，用于修改数据库中的表结构
        // 这里是向名为TABLE.NOTE的表中添加一个新的列NoteColumns.VERSION
        // 新列的数据类型为INTEGER（整数）
        // 该列不允许为空（NOT NULL）
        // 默认值为0（DEFAULT 0）
        db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
                + " INTEGER NOT NULL DEFAULT 0");
    }
}
