/*
 * 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;
    // Note content
    private String mContent;
    // Note mode
    private int mMode;

    private long mAlertDate;

    private long mModifiedDate;

    private int mBgColorId;

    private int mWidgetId;

    private int mWidgetType;

    private long mFolderId;

    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,
            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;

    private static final int DATA_CONTENT_COLUMN = 1;

    private static final int DATA_MIME_TYPE_COLUMN = 2;

    private static final int DATA_MODE_COLUMN = 3;

    private static final int NOTE_PARENT_ID_COLUMN = 0;

    private static final int NOTE_ALERTED_DATE_COLUMN = 1;

    private static final int NOTE_BG_COLOR_ID_COLUMN = 2;

    private static final int NOTE_WIDGET_ID_COLUMN = 3;

    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);
        // 检查查询结果是否为空
        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()方法加载笔记的其他数据
        loadNoteData();
    }

    private void loadNoteData() {
        // 通过内容解析器(ContentResolver)查询笔记的数据信息
        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)) {
                        // 如果是笔记类型的数据，获取内容和模式，并设置到相应的成员变量中
                        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)) {
                        // 如果是通话笔记类型的数据，设置通话数据ID到相应的成员变量中
                        mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
                    } 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) {
                    // 如果创建新的笔记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) {
            // 如果不同，更新当前提醒日期为传入的日期，并通过 mNote 对象将更新后的提醒日期同步到数据库中
            mAlertDate = date;
            mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
        }
        // 检查是否存在笔记设置状态监听器
        if (mNoteSettingStatusListener != null) {
            // 如果存在，调用监听器的 onClockAlertChanged 方法，通知提醒日期已更改，并传递新的日期和开关状态
            mNoteSettingStatusListener.onClockAlertChanged(date, set);
        }
    }

    public void markDeleted(boolean mark) {
        // 将笔记的删除状态更新为传入的标记值
        mIsDeleted = mark;
        // 检查是否存在与该笔记相关的小部件，并且小部件类型有效，并且存在笔记设置状态监听器
        if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
            // 如果条件满足，调用监听器的 onWidgetChanged 方法，通知小部件内容已更改
                mNoteSettingStatusListener.onWidgetChanged();
        }
    }

    public void setBgColorId(int id) {
        // 检查传入的颜色ID是否与当前背景颜色ID不同
        if (id != mBgColorId) {
            // 如果不同，更新当前背景颜色ID为传入的颜色ID
            mBgColorId = id;
            // 检查是否存在笔记设置状态监听器
            if (mNoteSettingStatusListener != null) {
                // 如果存在，调用监听器的 onBackgroundColorChanged 方法，通知背景颜色已更改
                mNoteSettingStatusListener.onBackgroundColorChanged();
            }
            // 通过 mNote 对象将更新后的背景颜色ID同步到数据库中
            mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
        }
    }

    public void setCheckListMode(int mode) {
        if (mMode != mode) {
            // 如果不同，更新当前模式为传入的模式

            // 检查是否存在笔记设置状态监听器
            if (mNoteSettingStatusListener != null) {
                // 如果存在，调用监听器的 onCheckListModeChanged 方法，通知检查清单模式已更改，并传递旧模式和新模式
                mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
            }
            // 将当前模式更新为传入的模式，并通过 mNote 对象将更新后的模式同步到数据库中
            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) {
        // 检查传入的小部件类型是否与当前小部件类型不同
        if (id != mWidgetId) {
            // 如果不同，更新当前小部件类型为传入的小部件类型
            mWidgetId = id;

            // 通过 mNote 对象将更新后的小部件类型同步到数据库中
            mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
        }
    }

    public void setWorkingText(String text) {
        // 检查传入的文本内容是否与当前内容不同
        if (!TextUtils.equals(mContent, text)) {
            // 如果不同，更新当前内容为传入的文本内容

            mContent = text;
            // 通过 mNote 对象将更新后的文本内容同步到数据库中
            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;
    }

    public int getBgColorResId() {
        return NoteBgResources.getNoteBgResource(mBgColorId);
    }

    public int getBgColorId() {
        return mBgColorId;
    }

    public int getTitleBgResId() {
        return NoteBgResources.getNoteTitleBgResource(mBgColorId);
    }

    public int getCheckListMode() {
        return mMode;
    }

    public long getNoteId() {
        return mNoteId;
    }

    public long getFolderId() {
        return mFolderId;
    }

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