/*
 * Copyright (C) 2022 - Florindo Smilari (spherIC)
 */
package ch.spherIC.recurvebowsight.ui.calcsight;

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

import com.google.android.material.tabs.TabLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import ch.spherIC.recurvebowsight.R;
import ch.spherIC.recurvebowsight.databinding.FragmentCalcsightBinding;

public class CalculateSightFragment extends Fragment {

    private FragmentCalcsightBinding binding;
    private CalculateSightCollectionAdapter calculateSightCollectionAdapter;
    private ViewPager2 viewPager;
    private ViewPager2.OnPageChangeCallback pageChangeCallback;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.binding = FragmentCalcsightBinding.inflate(inflater, container, false);
        View root = this.binding.getRoot();
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        TabLayout tabLayout = view.findViewById(R.id.calcSight_tabLayout);
        this.calculateSightCollectionAdapter = new CalculateSightCollectionAdapter(this, tabLayout.getTabCount());
        this.pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (positionOffset == 0.0f) {
                    TabLayout tabLayout = view.findViewById(R.id.calcSight_tabLayout);
                    tabLayout.getTabAt(position).select();
                }
            }
        };
        this.viewPager = view.findViewById(R.id.calcSight_viewPager);
        this.viewPager.setAdapter(this.calculateSightCollectionAdapter);
        this.viewPager.registerOnPageChangeCallback(this.pageChangeCallback);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (viewPager.getCurrentItem() != tab.getPosition()) {
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

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

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

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        this.binding = null;
        this.viewPager.unregisterOnPageChangeCallback(this.pageChangeCallback);
    }

    public void scrollToTab(int position) {
        this.viewPager.setCurrentItem(position);
    }
}