package com.wasu.cs.adapter;

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

import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

public class ContPagerAdapter extends PagerAdapter {
	
	private ViewInterface viewInterface = null;
	private List<Object> dataList;
	private SparseArray<View> pagerArr;
	
	public ContPagerAdapter(List<?> dataList) {
		this.dataList = new ArrayList<Object>();
		this.pagerArr = new SparseArray<View>();
		
		if(dataList != null) {
            this.dataList.clear();
            this.dataList.addAll(dataList);
    	}
	}

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

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}
	
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		if (viewInterface!=null&&pagerArr!=null) {
		View view = pagerArr.get(position);
		if(view == null) {
			
				view = viewInterface.getView(position, getItem(position), null, null);
				pagerArr.put(position, view);
			}
		container.addView(view);
		return view;
		}
		
		
		return null;
	}
	
	public Object getObject(int position) {
		if (pagerArr==null) {
			return null;
		}
		return pagerArr.get(position);
	}
	
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		if (pagerArr==null) {
			return;
		}
		container.removeView(pagerArr.get(position));
	}
	
	public void setViewInterface(ViewInterface viewInterface) {
		this.viewInterface = viewInterface;
	}
	
	public interface ViewInterface {

		public View getView(int position, Object dataObject,
				View convertView, ViewGroup parent);
	}
	
	public void releaseResources() {
		
		if(pagerArr != null) {
			pagerArr.clear();
		}
		
		viewInterface = null;
	}

}
