package com.wall.dream.wallpapers.View;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.wall.dream.wallpapers.databinding.View1HomeContainerBinding;

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

public class ViewHomeContainer extends Fragment {
    private View1HomeContainerBinding vb;
    private List<Fragment> topFragments = new ArrayList<>();

    public ViewHomeContainer() {
    }

    public static ViewHomeContainer newInstance() {
        return new ViewHomeContainer();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        vb = View1HomeContainerBinding.inflate(inflater, container, false);
        initTopTabs();
        return vb.getRoot();
    }

    private void initTopTabs() {
        // 顶部Fragment列表
        topFragments.add(ViewFeatured.newInstance()); // 精选
        topFragments.add(ViewMain.newInstance(0));    // 分类

        // 设置顶部ViewPager
        vb.topViewpager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return topFragments.get(position);
            }

            @Override
            public int getItemCount() {
                return topFragments.size();
            }
        });
        vb.topViewpager.setUserInputEnabled(true);

        // 设置顶部TabLayout
        vb.topTab.addTab(vb.topTab.newTab().setText("精选"));
        vb.topTab.addTab(vb.topTab.newTab().setText("分类"));

        // 顶部Tab切换监听
        vb.topTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vb.topViewpager.setCurrentItem(tab.getPosition(), true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        // ViewPager切换时同步Tab
        vb.topViewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                vb.topTab.selectTab(vb.topTab.getTabAt(position));
            }
        });
    }
}

