package com.wasu.cs.widget.mediacontrol.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zhangrm on 16-2-24.
 */
public class RecommendAdapter extends BaseAdapter {

    private ViewInterface viewInterface = null;
    private List<Object> dataList;
    public HashMap<Integer, Reference<View>> viewMap = new HashMap<Integer, Reference<View>>();

    public RecommendAdapter(List<?> dataList) {
        this.dataList = new ArrayList<Object>();

        if (dataList != null) {
            this.dataList.clear();
            this.dataList.addAll(dataList);
        }
    }

    public void setViewInterface(ViewInterface viewInterface) {
        this.viewInterface = viewInterface;
    }

    public void clearData() {
        this.dataList.clear();
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int position) {
        Object data = null;
        if (dataList.size() > position) {
            data = dataList.get(position);
        }
        return data;
    }

    public View getObject(int position) {
        Reference<View> ref = viewMap.get(position);
        if (ref == null) {
            return null;
        }

        return ref.get();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;

        if (viewInterface != null) {
            view = viewInterface.getView(position, getItem(position), convertView, parent);
        }

        viewMap.put(position, new WeakReference<View>(view));

        // viewMap.put(position, view);
        return view;
    }

    public interface ViewInterface {
        public View getView(int position, Object dataObject, View convertView, ViewGroup parent);
    }

}
