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

/**
 * WorkingNote 类处理与笔记相关的工作逻辑。它支持创建新笔记、加载现有笔记、设置笔记内容、
 * 管理笔记的背景色、提醒时间等,同时支持与小部件的交互。
 */
public class WorkingNote {
    private Note mNote;  // 代表笔记的 Note 对象
    private long mNoteId;  // 笔记的 ID
    private String mContent;  // 笔记的内容(文本)
    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 boolean mIsDeleted;  // 是否被标记为已删除
    private NoteSettingChangedListener mNoteSettingStatusListener;  // 设置变更监听器

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

    // 数据查询的列名数组
    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;

    /**
     * 构造一个新的工作笔记
     */
    private WorkingNote(Context context, long folderId) {
        mContext = context;
        mAlertDate = 0;
        mModifiedDate = System.currentTimeMillis();
        mFolderId = folderId;
        mNote = new Note();  // 创建一个新的 Note 对象
        mNoteId = 0;
        mIsDeleted = false;
        mMode = 0;
        mWidgetType = Notes.TYPE_WIDGET_INVALIDE;  // 默认无效的小部件类型
    }

    /**
     * 构造一个现有的工作笔记
     */
    private WorkingNote(Context context, long noteId, long folderId) {
        mContext = context;
        mNoteId = noteId;
        mFolderId = folderId;
        mIsDeleted = false;
        mNote = new Note();
        loadNote();  // 加载笔记数据
    }

    /**
     * 从数据库加载笔记的信息
     */
    private void loadNote() {
        // 从笔记内容 URI 中查询笔记的基本信息
        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();  // 加载笔记的内容数据
    }

    /**
     * 加载笔记的具体内容(如文本内容或通话记录等)
     */
    private void loadNoteData() {
        // 查询笔记的数据内容
        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));  // 设置文本数据ID
                    } 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);  // 设置小部件ID
        note.setWidgetType(widgetType);  // 设置小部件类型
        return note;
    }

    /**
     * 加载指定ID的工作笔记
     */
    public static WorkingNote load(Context context, long id) {
        return new WorkingNote(context, id, 0);
    }

    /**
     * 保存笔记
     */
    public synchronized boolean saveNote() {
        if (isWorthSaving()) {  // 如果笔记值得保存
            if (!existInDatabase()) {  // 如果笔记不存在数据库
                if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
                    Log.e(TAG, "Create new note fail with id:" + mNoteId);
                    return false;
                }
            }

            mNote.syncNote(mContext, mNoteId);  // 同步笔记内容到数据库

            // 如果笔记关联了小部件,更新小部件内容
            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() {
        return !(mIsDeleted || (TextUtils.isEmpty(mContent) && !existInDatabase()) 
                 || (existInDatabase() && !mNote.isLocalModified()));  // 判断笔记是否被删除或没有修改
    }

    // 其他设置方法(设置提醒时间、背景色、小部件等)
    public void setAlertDate(long date, boolean set) { ... }
    public void markDeleted(boolean mark) { ... }
    public void setBgColorId(int id) { ... }
    public void setCheckListMode(int mode) { ... }
    public void setWidgetType(int type) { ... }
    public void setWidgetId(int id) { ... }
    public void setWorkingText(String text) { ... }

    // 获取笔记内容、提醒时间、修改时间等信息
    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 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 { 
        void onBackgroundColorChanged();  // 背景色变更时调用
        void onClockAlertChanged(long date, boolean set);  // 提醒时间变更时调用
        void onWidgetChanged();  // 小部件变更时调用
        void onCheckListModeChanged(int oldMode, int newMode);  // 清单模式切换时调用
    }
}