package com.geek.demo.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.geek.demo.R;
import com.geek.demo.model.BannerData;
import com.geek.demo.utils.MyUtils;

import java.util.List;

public class BannerAdapter extends PagerAdapter {

    private Context context;
    private List<BannerData> data;

    public BannerAdapter(Context context, List<BannerData> data) {
        this.context = context;
        this.data = data;
    }

    public void setData(List<BannerData> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (data != null) {
            return data.size();
        }
        return 0;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View inflate = View.inflate(context, R.layout.item_banner, null);
        ImageView imageView = inflate.findViewById(R.id.iv_banner);
        TextView tvTitle = inflate.findViewById(R.id.tv_banner_title);
        final BannerData bannerData = data.get(position);
        tvTitle.setText(bannerData.title);
        MyUtils.loadImage(bannerData.imageUrl, imageView, context);

        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUtils.openUrl(context, bannerData.url);
            }
        });
        container.addView(inflate);
        return inflate;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

}
