/*
 * 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
    private long mNoteId; // 便签id
    // 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"; // 设置TAG

    private boolean mIsDeleted; // 表示是否被删除

    private NoteSettingChangedListener mNoteSettingStatusListener; // 表示便签设置状态

    public static final String[] DATA_PROJECTION = new String[] { // 用于指定需要从数据库查询的数据列
            DataColumns.ID,
            DataColumns.CONTENT,
            DataColumns.MIME_TYPE,
            DataColumns.DATA1,
            DataColumns.DATA2,
            DataColumns.DATA3,
            DataColumns.DATA4,
    };

    public static final String[] NOTE_PROJECTION = new String[] {
            NoteColumns.PARENT_ID,
            NoteColumns.ALERTED_DATE,
            NoteColumns.BG_COLOR_ID,
            NoteColumns.WIDGET_ID,
            NoteColumns.WIDGET_TYPE,
            NoteColumns.MODIFIED_DATE
    };

    private static final int DATA_ID_COLUMN = 0; // 表示查询数据的id列

    private static final int DATA_CONTENT_COLUMN = 1; // 表示查询数据的内容列

    private static final int DATA_MIME_TYPE_COLUMN = 2; // 表示查询数据的MIME类型列

    private static final int DATA_MODE_COLUMN = 3; // 表示查询数据的模式列

    private static final int NOTE_PARENT_ID_COLUMN = 0; // 表示查询便签的父文件夹id列

    private static final int NOTE_ALERTED_DATE_COLUMN = 1; // 表示便签的提醒日期列

    private static final int NOTE_BG_COLOR_ID_COLUMN = 2; // 表示便签的背景颜色id列

    private static final int NOTE_WIDGET_ID_COLUMN = 3; // 表示便签小组件id列

    private static final int NOTE_WIDGET_TYPE_COLUMN = 4; // 表示便签小组件类型列

    private static final int NOTE_MODIFIED_DATE_COLUMN = 5; // 表示便签最后修改日期列

    // New note construct
    private WorkingNote(Context context, long folderId) { // 新建便签的结构
        mContext = context;
        mAlertDate = 0;
        mModifiedDate = System.currentTimeMillis();
        mFolderId = folderId;
        mNote = new Note();
        mNoteId = 0;
        mIsDeleted = false;
        mMode = 0;
        mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
    }

    // Existing note construct
    private WorkingNote(Context context, long noteId, long folderId) { // 存在的的便签结构
        mContext = context;
        mNoteId = noteId;
        mFolderId = folderId;
        mIsDeleted = false;
        mNote = new Note();
        loadNote();
    }

    private void loadNote() { // 查询并加载当前便签的详细信息
        Cursor cursor = mContext.getContentResolver().query(
                ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
                null, null); // 返回一个Cursor对象

        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); // 抛出异常，表示未找到指定id的便签
        }
        loadNoteData(); // 加载便签内容和其他数据
    }

    private void loadNoteData() { // 加载便签内容数据
        Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
                DataColumns.NOTE_ID + "=?", new String[] { // 获取与便签id相对应的所有数据
                        String.valueOf(mNoteId)
                }, null); // 遍历Cursor对象所有数据

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
                    if (DataConstants.NOTE.equals(type)) { // 类型相对应则设置WorkingNote对象成员变量
                        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)); // 设置为Notes对象的成员变量
                    } 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, // 上下文对象、文件夹id、组件id、组件类型、默认背景颜色id
            int widgetType, int defaultBgColorId) { // 创建空白便签
        WorkingNote note = new WorkingNote(context, folderId); // 用上下文对象、父文件夹id创建WorkingNote
        note.setBgColorId(defaultBgColorId);
        note.setWidgetId(widgetId);
        note.setWidgetType(widgetType);
        return note; // 设置变量并返回
    }

    public static WorkingNote load(Context context, long id) { // 用上下文对象和id创建新的WorkingNote对象
        return new WorkingNote(context, id, 0);
    }

    public synchronized boolean saveNote() { // 保存便签
        if (isWorthSaving()) { // 判断是否保存
            if (!existInDatabase()) { // 是否存在与数据库
                if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { // 不存在则获取id
                    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)); // 更新数据库
        }
    }

    public void setWidgetId(int id) { // 设置组件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)); // 修改父文件夹id为呼叫记录id
    }

    public boolean hasClockAlert() {
        return (mAlertDate > 0 ? true : false);
    } // 是否设置提醒数据

    public String getContent() {
        return mContent;
    } // 获取内容

    public long getAlertDate() {
        return mAlertDate;
    } // 获取提醒时间

    public long getModifiedDate() {
        return mModifiedDate;
    } // 获取最后修改时间

    public int getBgColorResId() {
        return NoteBgResources.getNoteBgResource(mBgColorId);
    } // 获取背景资源id

    public int getBgColorId() {
        return mBgColorId;
    } // 获取背景颜色id

    public int getTitleBgResId() {
        return NoteBgResources.getNoteTitleBgResource(mBgColorId);
    } // 获取标题栏背景颜色资源id

    public int getCheckListMode() {
        return mMode;
    } // 获取检查清单模式

    public long getNoteId() {
        return mNoteId;
    } // 获取便签id

    public long getFolderId() {
        return mFolderId;
    } // 获取父文件夹id

    public int getWidgetId() {
        return mWidgetId;
    } // 获取组件id

    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); // 清单模式转为笔记模式时启动
    }
}
