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

//便签表连接器，继承了CursorAdapter，它为cursor和ListView提供了连接的桥梁
//NotesListAdapter实现的是鼠标和编辑便签链接的桥梁
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; //选择模式标记

    /*
    桌面widget属性
     */
    public static class AppWidgetAttribute {
        public int widgetId;
        public int widgetType;
    };

    /*
    构造器 初始化
     */
    public NotesListAdapter(Context context) {
        super(context, null);  //父类对象置空
        mSelectedIndex = new HashMap<Integer, Boolean>();
        mContext = context;
        mNotesCount = 0;
    }

    /*
    函数功能：新建一个视图来存储光标所指向的数据
    函数实现：使用兄弟类NotesListItem新建一个项目选项
     */
    @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) {
            //新建一个项目选项并且用bind跟将view和鼠标，内容，便签数据捆绑在一起
            NoteItemData itemData = new NoteItemData(context, cursor);
            ((NotesListItem) view).bind(context, itemData, mChoiceMode,
                    isSelectedItem(cursor.getPosition()));
        }
    }

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

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

    //函数功能：设置单项选项框
    //函数实现：重置下标并且根据参数mode设置选项
    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() {
        //创建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) {
                    //报错
                    Log.d(TAG, "Wrong item id, should not happen");
                } else {
                    //满足条件添加id
                    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  光标
                Cursor c = (Cursor) getItem(position);
                if (c != null) {
                    AppWidgetAttribute widget = new AppWidgetAttribute();
                    NoteItemData item = new NoteItemData(mContext, c);
                    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");
                    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()) {
            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);
    }

    //内容发生更改时调用
    @Override
    protected void onContentChanged() {
        super.onContentChanged();
        calcNotesCount();
    }

    //在activity光标发生局部变动的时候回调该函数计算便签的数量
    @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;
            }
        }
    }
}
