/*
 * 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.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import androidx.recyclerview.widget.RecyclerView;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;

import java.util.HashSet;

/**
 * 笔记RecyclerView适配器
 * 
 * 这个类继承自RecyclerView.Adapter，用于将数据库中的笔记数据绑定到RecyclerView中显示。
 * 它支持笔记的选择模式、批量操作以及与桌面小部件的关联。
 * 相比原NotesListAdapter，使用RecyclerView带来更好的性能和动画支持。
 * 
 * 主要功能：
 * 1. 将笔记数据绑定到NoteViewHolder视图
 * 2. 支持多选模式和批量选择操作
 * 3. 获取选中的笔记ID和关联的桌面小部件信息
 * 4. 统计笔记数量和选中数量
 * 5. 支持局部刷新和内置动画
 * 
 * @see NoteViewHolder
 * @see NoteItemData
 */
public class NotesRecyclerViewAdapter extends RecyclerView.Adapter<NoteViewHolder> {
    private static final String TAG = "NotesRecyclerViewAdapter";
    
    private Context mContext;
    private Cursor mCursor;
    private SparseArray<Boolean> mSelectedIndex;
    private int mNotesCount;
    private boolean mChoiceMode;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    
    /**
     * 桌面小部件属性类
     * 
     * 用于存储桌面小部件的ID和类型信息
     */
    public static class AppWidgetAttribute {
        public int widgetId;
        public int widgetType;
    }
    
    /**
     * 点击监听器接口
     */
    public interface OnItemClickListener {
        void onItemClick(View view, int position, long id);
    }
    
    /**
     * 长按监听器接口
     */
    public interface OnItemLongClickListener {
        boolean onItemLongClick(View view, int position, long id);
    }
    
    /**
     * 构造器
     * 
     * 初始化笔记列表适配器，创建选中状态Map和计数器
     * 
     * @param context 应用上下文，不能为 null
     */
    public NotesRecyclerViewAdapter(Context context) {
        mSelectedIndex = new SparseArray<>();
        mContext = context;
        mNotesCount = 0;
    }
    
    /**
     * 创建ViewHolder
     * 
     * @param parent 父视图组
     * @param viewType 视图类型
     * @return 新创建的NoteViewHolder对象
     */
    @Override
    public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext)
                .inflate(R.layout.note_item, parent, false);
        final NoteViewHolder holder = new NoteViewHolder(view);
        
        // 设置点击监听
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    int position = holder.getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        long id = getItemId(position);
                        mOnItemClickListener.onItemClick(v, position, id);
                    }
                }
            }
        });
        
        // 设置长按监听
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnItemLongClickListener != null) {
                    int position = holder.getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        long id = getItemId(position);
                        return mOnItemLongClickListener.onItemLongClick(v, position, id);
                    }
                }
                return false;
            }
        });
        
        return holder;
    }
    
    /**
     * 绑定数据到ViewHolder
     * 
     * 将数据库游标中的数据绑定到已存在的ViewHolder上
     * 
     * @param holder 需要绑定数据的ViewHolder
     * @param position 列表项位置
     */
    @Override
    public void onBindViewHolder(NoteViewHolder holder, int position) {
        if (mCursor != null && mCursor.moveToPosition(position)) {
            NoteItemData itemData = new NoteItemData(mContext, mCursor);
            
            // 绑定数据到视图
            bindViewHolder(holder, itemData, position);
        }
    }
    
    /**
     * 绑定ViewHolder数据
     * 
     * @param holder ViewHolder对象
     * @param data 笔记数据
     * @param position 位置
     */
    private void bindViewHolder(NoteViewHolder holder, NoteItemData data, int position) {
        // 处理复选框
        if (mChoiceMode && data.getType() == Notes.TYPE_NOTE) {
            holder.mCheckBox.setVisibility(View.VISIBLE);
            holder.mCheckBox.setChecked(isSelectedItem(position));
        } else {
            holder.mCheckBox.setVisibility(View.GONE);
        }
        
        // 处理提醒图标
        if (data.hasAlert()) {
            holder.mAlert.setImageResource(R.drawable.clock);
            holder.mAlert.setVisibility(View.VISIBLE);
        } else {
            holder.mAlert.setVisibility(View.GONE);
        }
        
        // 处理标题
        if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
            holder.mCallName.setVisibility(View.GONE);
            holder.mAlert.setVisibility(View.VISIBLE);
            holder.mTitle.setTextAppearance(mContext, R.style.TextAppearancePrimaryItem);
            holder.mTitle.setText(mContext.getString(R.string.call_record_folder_name)
                    + mContext.getString(R.string.format_folder_files_count, data.getNotesCount()));
            holder.mAlert.setImageResource(R.drawable.call_record);
        } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
            holder.mCallName.setVisibility(View.VISIBLE);
            holder.mCallName.setText(data.getCallName());
            holder.mTitle.setTextAppearance(mContext, R.style.TextAppearanceSecondaryItem);
            holder.mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
        } else {
            holder.mCallName.setVisibility(View.GONE);
            holder.mTitle.setTextAppearance(mContext, R.style.TextAppearancePrimaryItem);
            
            if (data.getType() == Notes.TYPE_FOLDER) {
                holder.mTitle.setText(data.getSnippet()
                        + mContext.getString(R.string.format_folder_files_count,
                                data.getNotesCount()));
                holder.mAlert.setVisibility(View.GONE);
            } else {
                holder.mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
                if (data.hasAlert()) {
                    holder.mAlert.setImageResource(R.drawable.clock);
                    holder.mAlert.setVisibility(View.VISIBLE);
                } else {
                    holder.mAlert.setVisibility(View.GONE);
                }
            }
        }
        
        // 设置时间
        holder.mTime.setText(android.text.format.DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
        
        // 设置背景
        setBackground(holder.itemView, data);
    }
    
    /**
     * 根据笔记项的位置和类型设置合适的背景资源
     * @param view 列表项视图
     * @param data 笔记数据
     */
    private void setBackground(View view, NoteItemData data) {
        int id = data.getBgColorId();
        if (data.getType() == Notes.TYPE_NOTE) {
            int bgRes;
            if (data.isSingle() || data.isOneFollowingFolder()) {
                bgRes = NoteItemBgResources.getNoteBgSingleRes(id);
            } else if (data.isLast()) {
                bgRes = NoteItemBgResources.getNoteBgLastRes(id);
            } else if (data.isFirst() || data.isMultiFollowingFolder()) {
                bgRes = NoteItemBgResources.getNoteBgFirstRes(id);
            } else {
                bgRes = NoteItemBgResources.getNoteBgNormalRes(id);
            }
            view.setBackgroundResource(bgRes);
        } else {
            view.setBackgroundResource(NoteItemBgResources.getFolderBgRes());
        }
    }
    
    /**
     * 获取列表项数量
     * 
     * @return 列表项数量，如果游标为null则返回0
     */
    @Override
    public int getItemCount() {
        return mCursor != null ? mCursor.getCount() : 0;
    }
    
    /**
     * 获取指定位置的列表项ID
     * 
     * @param position 列表项位置
     * @return 列表项ID，如果游标为null或位置无效则返回0
     */
    public long getItemId(int position) {
        if (mCursor != null && mCursor.moveToPosition(position)) {
            return mCursor.getLong(mCursor.getColumnIndexOrThrow(Notes.NoteColumns.ID));
        }
        return 0;
    }
    
    /**
     * 获取指定位置的列表项
     * 
     * @param position 列表项位置
     * @return 列表项对象，如果游标为null或位置无效则返回null
     */
    public Object getItem(int position) {
        if (mCursor != null && mCursor.moveToPosition(position)) {
            return mCursor;
        }
        return null;
    }
    
    /**
     * 设置指定位置的选中状态
     * 
     * @param position 列表项位置，从0开始
     * @param checked 是否选中
     */
    public void setCheckedItem(int position, boolean checked) {
        mSelectedIndex.put(position, checked);
        notifyItemChanged(position);
    }
    
    /**
     * 判断是否处于选择模式
     * 
     * @return 如果处于选择模式返回true，否则返回false
     */
    public boolean isInChoiceMode() {
        return mChoiceMode;
    }
    
    /**
     * 设置选择模式
     * 
     * @param mode true表示进入选择模式，false表示退出选择模式
     */
    public void setChoiceMode(boolean mode) {
        mSelectedIndex.clear();
        mChoiceMode = mode;
        notifyDataSetChanged();
    }
    
    /**
     * 全选或取消全选所有笔记
     * 
     * @param checked true表示全选，false表示取消全选
     */
    public void selectAll(boolean checked) {
        if (mCursor != null) {
            for (int i = 0; i < getItemCount(); i++) {
                if (mCursor.moveToPosition(i)) {
                    if (NoteItemData.getNoteType(mCursor) == Notes.TYPE_NOTE) {
                        mSelectedIndex.put(i, checked);
                    }
                }
            }
            notifyDataSetChanged();
        }
    }
    
    /**
     * 获取所有选中项的笔记ID集合
     * 
     * @return 包含所有选中笔记ID的HashSet集合，如果没有选中项则返回空集合
     */
    public HashSet<Long> getSelectedItemIds() {
        HashSet<Long> itemSet = new HashSet<>();
        for (int i = 0; i < mSelectedIndex.size(); i++) {
            int key = mSelectedIndex.keyAt(i);
            if (mSelectedIndex.get(key)) {
                long id = getItemId(key);
                if (id == Notes.ID_ROOT_FOLDER) {
                    Log.d(TAG, "Wrong item id, should not happen");
                } else {
                    itemSet.add(id);
                }
            }
        }
        return itemSet;
    }
    
    /**
     * 获取所有选中项关联的桌面小部件集合
     * 
     * @return 包含所有选中笔记关联的桌面小部件属性的HashSet集合，如果游标无效则返回null
     */
    public HashSet<AppWidgetAttribute> getSelectedWidget() {
        HashSet<AppWidgetAttribute> itemSet = new HashSet<>();
        for (int i = 0; i < mSelectedIndex.size(); i++) {
            int key = mSelectedIndex.keyAt(i);
            if (mSelectedIndex.get(key)) {
                Cursor c = (Cursor) getItem(key);
                if (c != null) {
                    AppWidgetAttribute widget = new AppWidgetAttribute();
                    NoteItemData item = new NoteItemData(mContext, c);
                    widget.widgetId = item.getWidgetId();
                    widget.widgetType = item.getWidgetType();
                    itemSet.add(widget);
                } else {
                    Log.e(TAG, "Invalid cursor");
                    return null;
                }
            }
        }
        return itemSet;
    }
    
    /**
     * 获取选中项的数量
     * 
     * @return 选中项的数量，如果没有选中项则返回0
     */
    public int getSelectedCount() {
        int count = 0;
        for (int i = 0; i < mSelectedIndex.size(); i++) {
            if (mSelectedIndex.get(mSelectedIndex.keyAt(i))) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 判断是否已全选所有笔记
     * 
     * @return 如果所有笔记都被选中且至少有一个笔记则返回true，否则返回false
     */
    public boolean isAllSelected() {
        int checkedCount = getSelectedCount();
        return (checkedCount != 0 && checkedCount == mNotesCount);
    }
    
    /**
     * 判断指定位置的项是否被选中
     * 
     * @param position 列表项位置，从0开始
     * @return 如果该项被选中返回true，否则返回false
     */
    public boolean isSelectedItem(int position) {
        return mSelectedIndex.get(position, false);
    }
    
    /**
     * 更换游标
     * 
     * @param newCursor 新的数据库游标
     */
    public Cursor swapCursor(Cursor newCursor) {
        Cursor oldCursor = mCursor;
        mCursor = newCursor;
        calcNotesCount();
        notifyDataSetChanged();
        return oldCursor;
    }
    
    /**
     * 计算笔记数量
     */
    private void calcNotesCount() {
        mNotesCount = 0;
        if (mCursor != null) {
            for (int i = 0; i < getItemCount(); i++) {
                if (mCursor.moveToPosition(i)) {
                    if (NoteItemData.getNoteType(mCursor) == Notes.TYPE_NOTE) {
                        mNotesCount++;
                    }
                }
            }
        }
    }
    
    /**
     * 设置点击监听器
     * 
     * @param listener 点击监听器
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }
    
    /**
     * 设置长按监听器
     * 
     * @param listener 长按监听器
     */
    public void setOnItemLongClickListener(OnItemLongClickListener listener) {
        mOnItemLongClickListener = listener;
    }
}
