/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)//该模块主要是用于存储Notes的数据，以及根据数据更改Notes结构体的变量
 *
 * 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 {// NotesDatabaseHelper类，继承于SQLiteOpenHelper类的子类。
    private static final String DB_NAME = "note.db";//定义数据库的名称为“note.db”

    private static final int DB_VERSION = 4;//数据库版本号

    public interface TABLE {//将接口分成note和data
        public static final String NOTE = "note";// 创建note表信息

        public static final String DATA = "data";//创建data表信息
    }

    private static final String TAG = "NotesDatabaseHelper";//创建一个表格用来储存标签编号

    private static NotesDatabaseHelper mInstance;//创建NotesDatabaseHelper的一个对象

    private static final String CREATE_NOTE_TABLE_SQL =//增加文件夹
        "CREATE TABLE " + TABLE.NOTE + "(" +//定义.减少文件夹
            NoteColumns.ID + " INTEGER PRIMARY KEY," +//文件夹插入Note后需要更改的数据的表格
            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," +//应用界面颜色选择
            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 ''," +//Note中数据删除更改的数据表格
            NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
            NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
            NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
            NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
            NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
            NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
            NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
            NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +// 数据库中需要存储的项目的名称，就相当于创建一个表格的表头的内容
        ")";

    private static final String CREATE_DATA_TABLE_SQL =//这是用于创建note中数据的表项的SQL语句
        "CREATE TABLE " + TABLE.DATA + "(" +//note删除数据触发
            DataColumns.ID + " INTEGER PRIMARY KEY," +
            DataColumns.MIME_TYPE + " TEXT NOT NULL," +
            DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
            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," +
            DataColumns.DATA2 + " INTEGER," +
            DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
            DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
            DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
        ")";//文件夹删除note触发

    private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =//创建数据的ID的索引
        "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//Increase增加文件
Decrease减少文件
     */
    private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//当note移动到文件夹中时，文件夹的数量增加的功能
        "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";//在文件夹中移入一个Note之后需要更改的数据的表格

    /**
     * Decrease folder's note count when move note from folder
     */
    private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//从文件夹中移出一个note时，更新数量
        "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";//在文件夹中插入一个Note之后需要更改的数据的表格

    /**
     * Increase folder's note count when insert new note to the folder//在文件夹中新增文件
     */
    private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =//在文件夹中新建note时，更新数量
        "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";//在文件夹中插入一个Note之后需要更改的数据的表格

    /**
     * Decrease folder's note count when delete note from the folder//在文件夹中删除文件
     */
    private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =//在文件夹中删除note时，更新文件夹的note数量
        "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";在文件夹中删除一个Note之后需要更改的数据的表格

    /**
     * Update note's content when insert data with type {@link DataConstants#NOTE}//在数据库中新增note或插入内容
     */
    private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =//当note插入新的数据时，更新note的内容，并更改表格
        "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";// 在文件夹中对一个Note导入新的数据之后需要更改的数据的表格

    /**
     * Update note's content when data with {@link DataConstants#NOTE} type has changed//note发生变化时触发update
     */
    private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =//当note的数据发生变化时，更新表格
        "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";//Note数据被修改后需要更改的数据的表格

    /**
     * Update note's content when data with {@link DataConstants#NOTE} type has deleted//当类型被删除时，更新数据库
     */
    private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =//当note的内容被删除时，更新表格的内容
        "CREATE TRIGGER update_note_content_on_delete " +
        " AFTER delete ON " + TABLE.DATA +
        " WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
        " BEGIN" +//当data删除之后对数据进行更新
        "  UPDATE " + TABLE.NOTE +
        "   SET " + NoteColumns.SNIPPET + "=''" +
        "  WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
        " END";// Note数据被删除后需要更改的数据的表格

    /**
     * Delete datas belong to note which has been deleted// 删除数据库中的数据，当这些数据在本地被删除
     */
    private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =//删除被删除的note的data
        "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 =//将垃圾文件夹里的note还原，并更新数据表格
        "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";// 还原垃圾桶中便签后需要更改的数据的表格

    public NotesDatabaseHelper(Context context) {//传入数据库的名称和版本
        super(context, DB_NAME, null, DB_VERSION);
    }

    public void createNoteTable(SQLiteDatabase db) {//创建数据库，储存属性
        db.execSQL(CREATE_NOTE_TABLE_SQL);
        reCreateNoteTableTriggers(db);
        createSystemFolder(db);
        Log.d(TAG, "note table has been created");//调用系统输出调试信息，Log.d()是debug的意思。
    }

    private void reCreateNoteTableTriggers(SQLiteDatabase db) {//创建一个储存标签属性的表格
        db.execSQL("DROP TRIGGER IF EXISTS increase_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");//创建删除数据的触发器
        db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");//创建插入文件夹的触发器
        db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");//创建删除note的触发器
        db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");//创建移除note的触发器

        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);//创建删除notes的触发器
        db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);//创建将回收站中的notes还原的触发器
    }

    private void createSystemFolder(SQLiteDatabase db) {//创建系统文件夹
        ContentValues values = new ContentValues();//新建 ContantValues对象，储存基本数据类型

        /**
         * call record foler for call notes//创建callnote对应的文件夹
         */
        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);// 将数据库ID与通话记录文件夹ID形成映射
        values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);//将数据库中数据类型与通话记录文件夹类型形成映射
        db.insert(TABLE.NOTE, null, values);//插入ContantValues对象

        /**
         * 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) {//创建数据表格，储存便签内容
        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) {//重新创建数据表格触发器
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
        db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");

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

    static synchronized NotesDatabaseHelper getInstance(Context context) {//如果NotesDatabaseHelper创建失败，就再创建一个，采取static synchronized类型，防止多线程发生错误
        if (mInstance == null) {
            mInstance = new NotesDatabaseHelper(context);
        }
        return mInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {//自动创建数据库
        createNoteTable(db);
        createDataTable(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本的更新，包括数据库内容的更改
        boolean reCreateTriggers = false;//是否重建的信号
        boolean skipV2 = false;//是否从V2升级到V3

        if (oldVersion == 1) {//判断当前版本是不是一代
            upgradeToV2(db);
            skipV2 = true; // this upgrade including the upgrade from v2 to v3
            oldVersion++;
        }

        if (oldVersion == 2 && !skipV2) {//判断旧版本是不是2号版本且没有跳过2号版本，就更新到3号版本
            upgradeToV3(db);
            reCreateTriggers = true;
            oldVersion++;
        }

        if (oldVersion == 3) {//如果旧版本号为3号，就更新到4号版本
            upgradeToV4(db);
            oldVersion++;
        }

        if (reCreateTriggers) {//重新创建的同时，创建新的note table和datatable
            reCreateNoteTableTriggers(db);
            reCreateDataTableTriggers(db);
        }

        if (oldVersion != newVersion) {//判断当前版本是不是最新的
            throw new IllegalStateException("Upgrade notes database to version " + newVersion
                    + "fails");
        }
    }

    private void upgradeToV2(SQLiteDatabase db) {//将数据库的版本更新到V2
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
        createNoteTable(db);
        createDataTable(db);
    }

    private void upgradeToV3(SQLiteDatabase db) {//数据库版本升级到V3
        // 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);
    }

    private void upgradeToV4(SQLiteDatabase db) {//数据库版本升级到V4
        db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
                + " INTEGER NOT NULL DEFAULT 0");
    }
}
