/*
 * 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.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

import net.micode.notes.data.Notes;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;


public class NotesListAdapter extends CursorAdapter {//继承了CursorAdapter
    private static final String TAG = "NotesListAdapter";
    private Context mContext;
    private HashMap<Integer, Boolean> mSelectedIndex;//HashMap是一个散列表，储存键值对的映射关系
    private int mNotesCount;
    private boolean mChoiceMode;//选择模式标志

    public static class AppWidgetAttribute {//桌面widget的属性，包括编号和类型
        public int widgetId;
        public int widgetType;
    };//父类对象置空

    public NotesListAdapter(Context context) {//初始化便签链接
        super(context, null);
        mSelectedIndex = new HashMap<Integer, Boolean>();
        mContext = context;//新建一个视图来存储光标所指向的数据
        mNotesCount = 0;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {//利用NotesListLtem类创建新布局
        return new NotesListItem(context);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {//将已经存在的视图和鼠标指向的数据进行捆绑
        if (view instanceof NotesListItem) {
            NoteItemData itemData = new NoteItemData(context, cursor);//新建一个项目选项并且用bind跟将view和鼠标，内容，便签数据捆绑在一起
            ((NotesListItem) view).bind(context, itemData, mChoiceMode,
                    isSelectedItem(cursor.getPosition()));
        }
    }

    public void setCheckedItem(final int position, final boolean checked) {//设置勾选框
        mSelectedIndex.put(position, checked);//根据定位和是否勾选设置下标
        notifyDataSetChanged();
    }

    public boolean isInChoiceMode() {
        return mChoiceMode;
    }//判断单选按钮是否勾选

    public void setChoiceMode(boolean mode) {//重置下标，并根据参数mode设置选项
        mSelectedIndex.clear();
        mChoiceMode = mode;
    }

    public void selectAll(boolean checked) {//选择全部选项，遍历所有光标可用的位置在判断为便签类型之后勾选单项框
        Cursor cursor = getCursor();
        for (int i = 0; i < getCount(); i++) {//历可用光标位置，如果光标移动且光标当前指向的便签项目类型为TYPE_NOTE则设置为勾选状态
            if (cursor.moveToPosition(i)) {
                if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
                    setCheckedItem(i, checked);
                }
            }
        }
    }

    public HashSet<Long> getSelectedItemIds() {//建立选择项目的ID的HASH表
        HashSet<Long> itemSet = new HashSet<Long>();
        for (Integer position : mSelectedIndex.keySet()) {//遍历所有的关键
            if (mSelectedIndex.get(position) == true) {
                Long id = getItemId(position);
                if (id == Notes.ID_ROOT_FOLDER) {//原文件不需要添加，则将id该下标假如选项集合中
                    Log.d(TAG, "Wrong item id, should not happen");
                } else {
                    itemSet.add(id);//将该id加入到选项集合当中
                }
            }
        }

        return itemSet;
    }

    public HashSet<AppWidgetAttribute> getSelectedWidget() {//建立桌面widget选项表
        HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
        for (Integer position : mSelectedIndex.keySet()) {//遍历被选中的列表
            if (mSelectedIndex.get(position) == true) {
                Cursor c = (Cursor) getItem(position);//获取条目
                if (c != null) {
                    AppWidgetAttribute widget = new AppWidgetAttribute();
                    NoteItemData item = new NoteItemData(mContext, c);//新建widget并更新ID和类型，最后添加到选项表中
                    widget.widgetId = item.getWidgetId();
                    widget.widgetType = item.getWidgetType();
                    itemSet.add(widget);//加入条目集合
                    /**
                     * Don't close cursor here, only the adapter could close it
                     */
                } else {
                    Log.e(TAG, "Invalid cursor");//设置标签，无效的cursor
                    return null;
                }
            }
        }
        return itemSet;
    }

    public int getSelectedCount() {//获取选项个数
        Collection<Boolean> values = mSelectedIndex.values();
        if (null == values) {
            return 0;
        }
        Iterator<Boolean> iter = values.iterator();//初始化迭代器
        int count = 0;
        while (iter.hasNext()) {//如果iter后面还有，则count加一
            if (true == iter.next()) {
                count++;
            }
        }
        return count;
    }

    public boolean isAllSelected() {//判断是否全选
        int checkedCount = getSelectedCount();
        return (checkedCount != 0 && checkedCount == mNotesCount);
    }

    public boolean isSelectedItem(final int position) {//判断是否为选项表
        if (null == mSelectedIndex.get(position)) {
            return false;
        }
        return mSelectedIndex.get(position);//判断Item是否被选中的状态
    }

    @Override
    protected void onContentChanged() {//activity内容变动时调用calcNotesCount计算便签数量
        super.onContentChanged();//执行父类函数
        calcNotesCount();
    }

    @Override
    public void changeCursor(Cursor cursor) {
        super.changeCursor(cursor);//重载父类函数
        calcNotesCount();
    }

    private void calcNotesCount() {//实现方式类似前面代码中的selectAll函数
        mNotesCount = 0;
        for (int i = 0; i < getCount(); i++) {//获取总数同时遍历
            Cursor c = (Cursor) getItem(i);
            if (c != null) {//判断语句，如果光标不是null，那么便得到信息，便签数目加1
                if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {//若选项的数据类型为便签类型，那么计数+1
                    mNotesCount++;
                }
            } else {
                Log.e(TAG, "Invalid cursor");//否则就将设置为无效的光标
                return;
            }
        }
    }
}
