package com.wasu.widgets.adapter;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;

import com.wasu.widgets.focuswidget.FocusRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 支持FocusRecyclerView的设置headerView，多选模式，焦点监听，长按，单击和焦点框绘制
 * Created by Danxingxi on 2016/3/31.
 */
public abstract class BaseFocusRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseFocusRecyclerViewHolder> {
    /**
     * header view type
     **/
    public static final int TYPE_HEADER = 0;
    /**
     * item view type
     **/
    public static final int TYPE_NORMAL = 1;
    /**
     * item view type
     * */
    public static final int TYPE_FOOTER = 2;
    private View mHeaderView;
    private View mFooterView;
    public OnItemListener mOnItemListener;
    /**
     * 保存处于选中状态的itemView的position
     **/
    private SparseBooleanArray selectedItems;

    protected FocusRecyclerView focusRecyclerView;

    //    private List<Model> mData = new ArrayList<Model>();
//
//    public void setData(List<? extends Model> data){
//        mData.clear();
//        mData.addAll(data);
//    }
    public BaseFocusRecyclerViewAdapter(FocusRecyclerView recyclerView) {
        if (recyclerView != null) {
            this.focusRecyclerView = recyclerView;
        } else {
            new IllegalArgumentException("Parent FocusRecycerView can't empty");
        }
        selectedItems = new SparseBooleanArray();
    }

    private List<T> mData = new ArrayList<T>();

    /**
     * 首次设置数据
     * @param data
     */
    public void setData(List<T> data) {
        mData.clear();
        mData.addAll(data);
    }

    /**
     * 添加数据并通知更新
     * @param data
     */
    public void addData(List<T> data){
        mData.addAll(data);
        notifyDataSetChanged();
    }

    /**
     * 清楚所有数据
     */
    public void clearData() {
        if (mData != null) {
            mData.clear();
        }
    }

    public T getItemData(int position) {
        T res = null;
        /**计算正确的位置**/
//        int realPos = (mHeaderView == null ? position : position - 1);
        int realPos = position;
        if (realPos < mData.size()) {
            res = mData.get(realPos);
        }

        return res;
    }

    public void setOnItemListener(OnItemListener li) {
        mOnItemListener = li;
    }

    /**
     * add header view
     *
     * @param headerView
     */
    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    /**
     * add footer view
     *
     * @param footerView
     * */
    public void setFooterView(View footerView){
        mFooterView = footerView;
        notifyItemInserted(getItemCount()-1);
    }

    /**
     * get header view
     *
     * @return
     */
    public View getHeaderView() {
        return mHeaderView;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0){
            if (mHeaderView != null){
                return TYPE_HEADER;
            }else {
                return TYPE_NORMAL;
            }
        }else if (position == getItemCount() -1){
            if (mFooterView != null){
                return TYPE_FOOTER;
            }else {
                return TYPE_NORMAL;
            }
        }
        return TYPE_NORMAL;
    }

    /**
     * itemView的选中状态和非选中状态切换并及时更新UI状态
     * 选中状态调用时就切换为非选中状态，反之对调状态
     *
     * @param position 用户点击的itemView的位置
     */
    public void toggleSelection(int position) {

        /**计算正确的位置**/
        int realPos = (mHeaderView == null ? position : position - 1);

        position = realPos;

        if (selectedItems.get(position, false)) {
            selectedItems.delete(position);
        } else {
            selectedItems.put(position, true);
        }
        /*这个更新UI会使焦点闪烁一下*/
//        notifyItemChanged(position);
    }

    /**
     * 判断这个位置的item是处于选中状态
     *
     * @param position Position of the item to check
     * @return true if the item is selected, false otherwise
     */
    public boolean isSelected(int position) {
        /**计算正确的位置**/
        int realPos = (mHeaderView == null ? position : position - 1);

        return getSelectedItems().contains(realPos);
    }

    /**
     * 清除所有Item的选中状态
     */
    public void clearSelection() {
        List<Integer> selection = getSelectedItems();
        selectedItems.clear();
        notifyDataSetChanged();
//        for (Integer i : selection) {
//            notifyItemChanged(i);
//        }
    }

    /**
     * 获得所有选中状态item的position集合
     *
     * @return
     */
    public List<Integer> getSelectedItems() {
        List<Integer> items = new ArrayList<>(selectedItems.size());
        for (int i = 0; i < selectedItems.size(); ++i) {
            /*我们使用keyAt可以取到position，当然也可以使用valueAt取到value值，显然这个集合中的value都为true*/
            items.add(selectedItems.keyAt(i));
        }
        return items;
    }

    /**
     * 获得item的位置
     *
     * @param holder
     * @return
     */
    public int getRealPosition(BaseFocusRecyclerViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }

    @Override
    public BaseFocusRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER)
            return new HeaderViewHolderFocus(mHeaderView);
        if (mHeaderView != null && viewType == TYPE_FOOTER)
            return new HeaderViewHolderFocus(mFooterView);
        BaseFocusRecyclerViewHolder viewHolder = createItem(parent, viewType);
        if(viewHolder!=null){

        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final BaseFocusRecyclerViewHolder holder, int position) {
        /**如果是header view就直接返回，不需要绑定数据**/
        if (getItemViewType(position) == TYPE_HEADER) return;
        if (getItemViewType(position) == TYPE_FOOTER) return;
        final int pos = getRealPosition(holder);
        bindData(holder, pos);
    }

    @Override
    public int getItemCount() {
        if (mHeaderView != null && mFooterView != null){
            return mData.size() + 2;
        }else if(mHeaderView != null || mFooterView != null){
            return mData.size() + 1;
        }else {
            return mData.size();
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (getItemViewType(position) == TYPE_HEADER || getItemViewType(position) == TYPE_FOOTER){
                        return gridManager.getSpanCount();
                    }else {
                        return 1;
                    }
                }
            });
        }
    }

    @Override
    public void onViewAttachedToWindow(BaseFocusRecyclerViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        if (lp != null
                && lp instanceof StaggeredGridLayoutManager.LayoutParams
                && holder.getLayoutPosition() == 0) {
            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
            p.setFullSpan(true);
        }
    }

    /**
     * 创建item view
     *
     * @param parent
     * @param viewType
     * @return
     */
    protected abstract BaseFocusRecyclerViewHolder createItem(ViewGroup parent, int viewType);

    /**
     * 绑定数据
     *
     * @param holder
     * @param position
     */
    protected abstract void bindData(BaseFocusRecyclerViewHolder holder, int position);

    /**
     * header view ViewHolder
     */
    class HeaderViewHolderFocus extends BaseFocusRecyclerViewHolder {

        public HeaderViewHolderFocus(View itemView) {
            super(itemView, null, null);
        }

        @Override
        protected View getView() {
            return null;
        }
    }

    /**
     * item 点击事件接口
     *
     */
    public interface OnItemListener {
        /**
         * 单击监听
         **/
        void onItemClick(int position);

        /**
         * 长按监听
         **/
        void onItemLongClick(int position);

        /**
         * 焦点监听
         **/
        void onItemFocusChange(View itemView, int position, boolean hasFocus);
    }

    /**
     * 获取ItemView的parent也就是FocusRecyclerView
     * @return
     */
    protected FocusRecyclerView getItemParent(){
        return focusRecyclerView;
    }

    /**
     * 获取ItemView的监听器
     * @return
     */
    public OnItemListener getItemListener() {
        return mOnItemListener;
    }

}

