package com.ihaoin.hooloo.device.component;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.ihaoin.hooloo.device.util.CollectionUtils;

import java.util.List;

public class IntroViewPager extends ViewPager {
    public IntroViewPager(@NonNull Context context) {
        super(context);
    }

    public IntroViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (getAdapter() == null) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int index = getCurrentItem();
        int height = 0;
        View v = getView(index);
        if (v != null) {
            v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            height = v.getMeasuredHeight();
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private List<View> introViews;

    public void setIntroViews(List<View> introViews) {
        this.introViews = introViews;
        this.setAdapter(pagerAdapter);
    }

    public View getView(int index) {
        if (CollectionUtils.isEmpty(introViews)) {
            return null;
        }
        return introViews.get(index);
    }

    public int getCount() {
        if (pagerAdapter == null) {
            return 0;
        }
        return pagerAdapter.getCount();
    }

    private PagerAdapter pagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return CollectionUtils.isEmpty(introViews) ? 0 : introViews.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

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

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            if (CollectionUtils.isEmpty(introViews)) {
                return null;
            }
            View view = introViews.get(position);
            container.addView(view);
            return view;
        }
    };
}
