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

import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
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.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;


public class WorkingNote {
    // Note for the working note（工作笔记类)
    private Note mNote;// 笔记
    // Note Id/笔记ID
    private long mNoteId;
    // Note content笔记内容
    private String mContent;
    // Note mode笔记模式
    private int mMode;

    private long mAlertDate;// 提醒日期

    private long mModifiedDate;// 修改日期

    private int mBgColorId;// 背景颜色ID

    private int mWidgetId;// 小部件ID

    private int mWidgetType;// 小部件类型

    private long mFolderId;// 文件夹ID

    private Context mContext;// 上下文

    private static final String TAG = "WorkingNote";// 标签

    private boolean mIsDeleted;// 是否已删除

    private NoteSettingChangedListener mNoteSettingStatusListener;// 笔记设置改变监听器

    public static final String[] DATA_PROJECTION = new String[] {// 查询数据时需要返回的列名数组
            DataColumns.ID,// ID列
            DataColumns.CONTENT, // 内容列
            DataColumns.MIME_TYPE, // MIME类型列
            DataColumns.DATA1, // 数据列1
            DataColumns.DATA2,// 数据列2
            DataColumns.DATA3, // 数据列3
            DataColumns.DATA4,// 数据列4
    };

    public static final String[] NOTE_PROJECTION = new String[] {
            NoteColumns.PARENT_ID,// 父ID列
            NoteColumns.ALERTED_DATE,// 提醒日期列
            NoteColumns.BG_COLOR_ID,// 背景颜色ID列
            NoteColumns.WIDGET_ID,// 小部件ID列
            NoteColumns.WIDGET_TYPE,// 小部件类型列
            NoteColumns.MODIFIED_DATE // 修改日期列
    };

    private static final int DATA_ID_COLUMN = 0;// 数据表中数据ID列的索引，常量整数值为0


    private static final int DATA_CONTENT_COLUMN = 1;  // 数据表中数据内容列的索引，常量整数值为1


    private static final int DATA_MIME_TYPE_COLUMN = 2;// 数据表中数据MIME类型列的索引，常量整数值为2


    private static final int DATA_MODE_COLUMN = 3; // 数据表中数据模式列的索引，常量整数值为3


    private static final int NOTE_PARENT_ID_COLUMN = 0; // 笔记表中笔记父ID列的索引，常量整数值为0

    private static final int NOTE_ALERTED_DATE_COLUMN = 1;// 笔记表中笔记提醒日期列的索引，常量整数值为1

    private static final int NOTE_BG_COLOR_ID_COLUMN = 2;// 笔记表中笔记背景色ID列的索引，常量整数值为2

    private static final int NOTE_WIDGET_ID_COLUMN = 3; // 笔记表中笔记小部件ID列的索引，常量整数值为3

    private static final int NOTE_WIDGET_TYPE_COLUMN = 4;// 笔记表中笔记小部件类型列的索引，常量整数值为4

    private static final int NOTE_MODIFIED_DATE_COLUMN = 5;// 笔记表中笔记修改日期列的索引，常量整数值为5

    // New note construct创建新的笔记构造函数，传入上下文和文件夹ID
    private WorkingNote(Context context, long folderId) {
        mContext = context;// 初始化上下文
        mAlertDate = 0;// 提醒日期设置为0
        mModifiedDate = System.currentTimeMillis(); // 修改日期设置为当前时间
        mFolderId = folderId;// 设置文件夹ID
        mNote = new Note(); // 创建一个新的Note对象
        mNoteId = 0;// 设置笔记ID为0
        mIsDeleted = false;// 设置是否已删除为false
        mMode = 0;// 设置工作模式为0
        mWidgetType = Notes.TYPE_WIDGET_INVALIDE;// 设置小部件类型为无效类型
    }

    // Existing note construct加载现有笔记的构造函数，传入上下文、笔记ID和文件夹ID
    private WorkingNote(Context context, long noteId, long folderId) {
        mContext = context; // 初始化上下文
        mNoteId = noteId;// 设置笔记ID
        mFolderId = folderId;---------------------------// 设置文件夹ID
        mIsDeleted = false;// 设置是否已删除为false
        mNote = new Note(); // 创建一个新的Note对象
        loadNote();// 加载现有笔记
    }

    private void loadNote() {// 通过笔记ID查询笔记的游标
        Cursor cursor = mContext.getContentResolver().query(// 通过笔记ID查询笔记的游标
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
                null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {// 从游标中获取笔记的相关信息
                mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
                mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
                mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
                mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
                mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
                mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
            }
            cursor.close();
        } else {// 如果找不到笔记，则记录错误日志并抛出异常
            Log.e(TAG, "No note with id:" + mNoteId);
            throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
        }// 加载笔记的数据
        loadNoteData();
    }

    private void loadNoteData() {  // 通过笔记ID查询笔记数据的游标
        Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
                DataColumns.NOTE_ID + "=?", new String[] {
                    String.valueOf(mNoteId)
                }, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {// 获取笔记数据的类型
                    String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
                    if (DataConstants.NOTE.equals(type)) {// 如果是笔记文本数据，则获取内容和模式，并设置笔记的文本数据ID
                        mContent = cursor.getString(DATA_CONTENT_COLUMN);
                        mMode = cursor.getInt(DATA_MODE_COLUMN);
                        mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
                    } else if (DataConstants.CALL_NOTE.equals(type)) {
                        mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));// 如果是电话笔记数据，则设置笔记的电话数据ID
                    } else {
                        Log.d(TAG, "Wrong note type with type:" + type);
                    }// 如果是其他类型的笔记数据，则记录错误日志
                } while (cursor.moveToNext());
            }
            cursor.close();
        } else {  // 如果找不到笔记数据，则记录错误日志并抛出异常
            Log.e(TAG, "No data with id:" + mNoteId);
            throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
        }
    }
    // 创建一个空笔记
    public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
            int widgetType, int defaultBgColorId) {
        WorkingNote note = new WorkingNote(context, folderId);
        note.setBgColorId(defaultBgColorId);
        note.setWidgetId(widgetId);
        note.setWidgetType(widgetType);
        return note;
    }
    // 加载笔记
    public static WorkingNote load(Context context, long id) {
        return new WorkingNote(context, id, 0);
    }
    // 保存笔记
    public synchronized boolean saveNote() {
        if (isWorthSaving()) {
            if (!existInDatabase()) {// 如果笔记还不存在于数据库中，则为其生成一个新的ID
                if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
                    Log.e(TAG, "Create new note fail with id:" + mNoteId);
                    return false;
                }
            }
            // 将笔记同步到数据库中
            mNote.syncNote(mContext, mNoteId);

            /**
             * Update widget content if there exist any widget of this note如果笔记存在小部件，则更新小部件的内容
             */
            if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                    && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
                    && mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onWidgetChanged();
            }
            return true;
        } else {
            return false;
        }
    }
    // 判断笔记是否已经存在于数据库中
    public boolean existInDatabase() {
        return mNoteId > 0;
    }
    // 判断笔记是否值得保存
    private boolean isWorthSaving() {
        if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
                || (existInDatabase() && !mNote.isLocalModified())) {
            return false;
        } else {
            return true;
        }
    }
    // 设置笔记设置状态改变的监听器
    public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
        mNoteSettingStatusListener = l;
    }
    // 设置提醒日期
    public void setAlertDate(long date, boolean set) {
        if (date != mAlertDate) {
            mAlertDate = date;
            mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
        }
        if (mNoteSettingStatusListener != null) {
            mNoteSettingStatusListener.onClockAlertChanged(date, set);
        }
    }
    // 标记笔记是否被删除
    public void markDeleted(boolean mark) {
        mIsDeleted = mark;
        if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onWidgetChanged();
        }
    }
    // 设置笔记的背景颜色
    public void setBgColorId(int id) {
        if (id != mBgColorId) {
            mBgColorId = id;
            if (mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onBackgroundColorChanged();
            }
            mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
        }
    }
    // 设置笔记的检查列表模式
    public void setCheckListMode(int mode) {
        if (mMode != mode) {
            if (mNoteSettingStatusListener != null) {
                mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
            }
            mMode = mode;
            mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
        }
    }
    // 设置笔记的小部件类型
    public void setWidgetType(int type) {
        if (type != mWidgetType) {
            mWidgetType = type;
            mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
        }
    }
    // 设置笔记的小部件ID
    public void setWidgetId(int id) {
        if (id != mWidgetId) {
            mWidgetId = id;
            mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
        }
    }
    //设置文本内容
    public void setWorkingText(String text) {
        if (!TextUtils.equals(mContent, text)) {
            mContent = text;
            mNote.setTextData(DataColumns.CONTENT, mContent);
        }
    }
    //这是一个将笔记转换为电话记录的方法。它包含电话号码和通话日期，并更新笔记对象的值
    public void convertToCallNote(String phoneNumber, long callDate) {
        mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
        mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
        mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
    }
    //指示笔记是否有闹钟提醒
    public boolean hasClockAlert() {
        return (mAlertDate > 0 ? true : false);
    }
    // 返回笔记的文本内容
    public String getContent() {
        return mContent;
    }
    // 返回笔记的警报日期
    public long getAlertDate() {
        return mAlertDate;
    }
    // 返回笔记的修改日期
    public long getModifiedDate() {
        return mModifiedDate;
    }
    // 返回笔记的背景颜色资源ID
    public int getBgColorResId() {
        return NoteBgResources.getNoteBgResource(mBgColorId);
    }
    // 返回笔记的背景颜色ID
    public int getBgColorId() {
        return mBgColorId;
    }
    // 返回笔记标题的背景颜色资源ID
    public int getTitleBgResId() {
        return NoteBgResources.getNoteTitleBgResource(mBgColorId);
    }
    // 返回笔记的检查清单模式
    public int getCheckListMode() {
        return mMode;
    }
    // 返回笔记的ID
    public long getNoteId() {
        return mNoteId;
    }
    // 返回笔记所在文件夹的ID
    public long getFolderId() {
        return mFolderId;
    }
    // 返回笔记所属的小部件ID
    public int getWidgetId() {
        return mWidgetId;
    }
    // 返回笔记所属的小部件类型
    public int getWidgetType() {
        return mWidgetType;
    }

    public interface NoteSettingChangedListener {
        /**
         * Called when the background color of current note has just changed
         */
        void onBackgroundColorChanged();

        /**
         * Called when user set clock
         */
        void onClockAlertChanged(long date, boolean set);

        /**
         * Call when user create note from widget
         */
        void onWidgetChanged();

        /**
         * Call when switch between check list mode and normal mode
         * @param oldMode is previous mode before change
         * @param newMode is new mode
         */
        void onCheckListModeChanged(int oldMode, int newMode);
    }
}
