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

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;

/**
 * 笔记项数据类
 * 封装笔记列表项的所有数据信息，包括基本属性、位置状态等
 */
public class NoteItemData {
    // 数据库查询投影数组，定义需要查询的列
    static final String [] PROJECTION = new String [] {
        NoteColumns.ID,                 // ID列
        NoteColumns.ALERTED_DATE,       // 提醒日期列
        NoteColumns.BG_COLOR_ID,        // 背景颜色ID列
        NoteColumns.CREATED_DATE,       // 创建日期列
        NoteColumns.HAS_ATTACHMENT,     // 是否有附件列
        NoteColumns.MODIFIED_DATE,      // 修改日期列
        NoteColumns.NOTES_COUNT,        // 笔记数量列
        NoteColumns.PARENT_ID,          // 父ID列
        NoteColumns.SNIPPET,            // 摘要列
        NoteColumns.TYPE,               // 类型列
        NoteColumns.WIDGET_ID,          // 小部件ID列
        NoteColumns.WIDGET_TYPE,        // 小部件类型列
    };

    // 列索引常量定义
    private static final int ID_COLUMN                    = 0;   // ID列索引
    private static final int ALERTED_DATE_COLUMN          = 1;   // 提醒日期列索引
    private static final int BG_COLOR_ID_COLUMN           = 2;   // 背景颜色ID列索引
    private static final int CREATED_DATE_COLUMN          = 3;   // 创建日期列索引
    private static final int HAS_ATTACHMENT_COLUMN        = 4;   // 是否有附件列索引
    private static final int MODIFIED_DATE_COLUMN         = 5;   // 修改日期列索引
    private static final int NOTES_COUNT_COLUMN           = 6;   // 笔记数量列索引
    private static final int PARENT_ID_COLUMN             = 7;   // 父ID列索引
    private static final int SNIPPET_COLUMN               = 8;   // 摘要列索引
    private static final int TYPE_COLUMN                  = 9;   // 类型列索引
    private static final int WIDGET_ID_COLUMN             = 10;  // 小部件ID列索引
    private static final int WIDGET_TYPE_COLUMN           = 11;  // 小部件类型列索引

    // 基本数据属性
    private long mId;               // 笔记ID
    private long mAlertDate;        // 提醒日期
    private int mBgColorId;         // 背景颜色ID
    private long mCreatedDate;      // 创建日期
    private boolean mHasAttachment; // 是否有附件
    private long mModifiedDate;     // 修改日期
    private int mNotesCount;        // 笔记数量（用于文件夹）
    private long mParentId;         // 父ID
    private String mSnippet;        // 摘要内容
    private int mType;              // 类型（笔记/文件夹/系统）
    private int mWidgetId;          // 小部件ID
    private int mWidgetType;        // 小部件类型
    private String mName;           // 联系人姓名（通话记录用）
    private String mPhoneNumber;    // 电话号码（通话记录用）

    // 位置状态属性
    private boolean mIsLastItem;                    // 是否为最后一项
    private boolean mIsFirstItem;                   // 是否为第一项
    private boolean mIsOnlyOneItem;                 // 是否为唯一一项
    private boolean mIsOneNoteFollowingFolder;      // 是否为文件夹后的单个笔记
    private boolean mIsMultiNotesFollowingFolder;   // 是否为文件夹后的多个笔记之一

    /**
     * 构造方法
     * 从游标中读取数据并初始化笔记项数据
     * @param context 上下文对象
     * @param cursor 数据库游标
     */
    public NoteItemData(Context context, Cursor cursor) {
        // 从游标中读取基本数据
        mId = cursor.getLong(ID_COLUMN);
        mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
        mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
        mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
        mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
        mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
        mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
        mParentId = cursor.getLong(PARENT_ID_COLUMN);
        mSnippet = cursor.getString(SNIPPET_COLUMN);
        // 移除摘要中的选中/未选中标记
        mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
                NoteEditActivity.TAG_UNCHECKED, "");
        mType = cursor.getInt(TYPE_COLUMN);
        mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
        mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);

        // 处理通话记录相关信息
        mPhoneNumber = "";
        if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
            // 获取通话记录的电话号码
            mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
            if (!TextUtils.isEmpty(mPhoneNumber)) {
                // 根据电话号码获取联系人姓名
                mName = Contact.getContact(context, mPhoneNumber);
                if (mName == null) {
                    mName = mPhoneNumber;
                }
            }
        }

        // 确保姓名不为空
        if (mName == null) {
            mName = "";
        }
        // 检查项在列表中的位置状态
        checkPostion(cursor);
    }

    private void checkPostion(Cursor cursor) {
        mIsLastItem = cursor.isLast() ? true : false;
        mIsFirstItem = cursor.isFirst() ? true : false;
        mIsOnlyOneItem = (cursor.getCount() == 1);
        mIsMultiNotesFollowingFolder = false;
        mIsOneNoteFollowingFolder = false;

        if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
            int position = cursor.getPosition();
            if (cursor.moveToPrevious()) {
                if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
                        || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
                    if (cursor.getCount() > (position + 1)) {
                        mIsMultiNotesFollowingFolder = true;
                    } else {
                        mIsOneNoteFollowingFolder = true;
                    }
                }
                if (!cursor.moveToNext()) {
                    throw new IllegalStateException("cursor move to previous but can't move back");
                }
            }
        }
    }

    public boolean isOneFollowingFolder() {
        return mIsOneNoteFollowingFolder;
    }

    public boolean isMultiFollowingFolder() {
        return mIsMultiNotesFollowingFolder;
    }

    public boolean isLast() {
        return mIsLastItem;
    }

    public String getCallName() {
        return mName;
    }

    public boolean isFirst() {
        return mIsFirstItem;
    }

    public boolean isSingle() {
        return mIsOnlyOneItem;
    }

    public long getId() {
        return mId;
    }

    public long getAlertDate() {
        return mAlertDate;
    }

    public long getCreatedDate() {
        return mCreatedDate;
    }

    public boolean hasAttachment() {
        return mHasAttachment;
    }

    public long getModifiedDate() {
        return mModifiedDate;
    }

    public int getBgColorId() {
        return mBgColorId;
    }

    public long getParentId() {
        return mParentId;
    }

    public int getNotesCount() {
        return mNotesCount;
    }

    public long getFolderId () {
        return mParentId;
    }

    public int getType() {
        return mType;
    }

    public int getWidgetType() {
        return mWidgetType;
    }

    public int getWidgetId() {
        return mWidgetId;
    }

    public String getSnippet() {
        return mSnippet;
    }

    public boolean hasAlert() {
        return (mAlertDate > 0);
    }

    public boolean isCallRecord() {
        return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
    }

    public static int getNoteType(Cursor cursor) {
        return cursor.getInt(TYPE_COLUMN);
    }
}
