/*
 * 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 {
    private static final String TAG = "NotesListAdapter";
    private Context mContext; 
    private HashMap<Integer, Boolean> mSelectedIndex; //所选索引
    private int mNotesCount;     //便签数量
    private boolean mChoiceMode; //选择模式

    public static class AppWidgetAttribute {
        public int widgetId;
        public int widgetType;
    };

    //初始化NotesListAdapter
    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) {
        //新建项目选项
        return new NotesListItem(context);
    }

    @Override
    //绑定视图 将视图于光标进行捆绑
    public void bindView(View view, Context context, Cursor cursor) {
        if (view instanceof NotesListItem) {
            //检查视图是否为NotesListItem类型
            //是的话则创建一个新的 NoteItemData 对象并使用它来绑定视图
            NoteItemData itemData = new NoteItemData(context, cursor);
            ((NotesListItem) view).bind(context, itemData, mChoiceMode,
                    isSelectedItem(cursor.getPosition()));
        }
    }

    //设置勾选框
    public void setCheckedItem(final int position, final boolean checked) {
        //根据position，checked来设置下标
        mSelectedIndex.put(position, checked);
        //刷新activity
        notifyDataSetChanged();
    }

    //判断是否处于选择模式
    public boolean isInChoiceMode() {
        return mChoiceMode;
    }

    //设置选择模式
    public void setChoiceMode(boolean mode) {
        mSelectedIndex.clear();
        mChoiceMode = mode;
    }

    //选择全部选项
    public void selectAll(boolean checked) {
        //获取光标位置
        Cursor cursor = getCursor();
        for (int i = 0; i < getCount(); i++) {
            //遍历所有光标可用的位置在判断为便签类型之后勾选单项框
            if (cursor.moveToPosition(i)) {
                if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
                    setCheckedItem(i, checked);
                }
            }
        }
    }

    //建立选择项的下标列表
    public HashSet<Long> getSelectedItemIds() {
        HashSet<Long> itemSet = new HashSet<Long>();//哈希表
        for (Integer position : mSelectedIndex.keySet()) {//遍历 mSelectedIndex 变量中的所有位置
            if (mSelectedIndex.get(position) == true) {//如果光标位置为true
                Long id = getItemId(position);
                if (id == Notes.ID_ROOT_FOLDER) {
                    Log.d(TAG, "Wrong item id, should not happen");
                } else {//否则添加到itemSet中
                    itemSet.add(id);
                }
            }
        }

        return itemSet;
    }

    //建立桌面Widget的选项表
    public HashSet<AppWidgetAttribute> getSelectedWidget() {
        HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
        for (Integer position : mSelectedIndex.keySet()) {
            if (mSelectedIndex.get(position) == true) {
                Cursor c = (Cursor) getItem(position);
                if (c != null) {
                    //光标非空则建立widget并编辑下标和类型
                    AppWidgetAttribute widget = new AppWidgetAttribute();
                    NoteItemData item = new NoteItemData(mContext, c);
                    widget.widgetId = item.getWidgetId();
                    widget.widgetType = item.getWidgetType();
                    //添加到itemSet
                    itemSet.add(widget);
                    /**
                     * Don't close cursor here, only the adapter could close it
                     * 不要在此处关闭光标，只有适配器可以关闭它
                     */
                } else {
                    Log.e(TAG, "Invalid cursor");
                    return null;
                }
            }
        }
        return itemSet;
    }

    //获取选项个数
    public int getSelectedCount() {
        //获取下标值
        Collection<Boolean> values = mSelectedIndex.values();
        if (null == values) { //values为空返回0
            return 0;
        }
        //初始化
        Iterator<Boolean> iter = values.iterator();
        int count = 0;
        while (iter.hasNext()) {
            if (true == iter.next()) {
                count++;
            }
        }
        return count;
    }

    //判断是否被全部选中
    public boolean isAllSelected() {
        int checkedCount = getSelectedCount();
        //返回比较是否检查数等于便签数且不为0
        return (checkedCount != 0 && checkedCount == mNotesCount);
    }

    //判断是否为选项表
    public boolean isSelectedItem(final int position) {
        //获取的光标位置是否为空
        if (null == mSelectedIndex.get(position)) {
            return false;
        }
        return mSelectedIndex.get(position);
    }

    @Override
    //在适配器内容发生更改时调用计算便签数量
    protected void onContentChanged() {
        super.onContentChanged();
        calcNotesCount();
    }

    @Override
    //光标更改时计算便签数量
    public void changeCursor(Cursor cursor) {
        super.changeCursor(cursor);
        calcNotesCount();
    }

    //计算便签数量
    private void calcNotesCount() {
        mNotesCount = 0;
        for (int i = 0; i < getCount(); i++) {
            Cursor c = (Cursor) getItem(i);
            if (c != null) {
                if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
                    mNotesCount++;
                }
            } else {
                Log.e(TAG, "Invalid cursor");
                return;
            }
        }
    }
}
