package com.atmob.voiceai.module.history;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.atmob.app.lib.base.BaseFragment;
import com.atmob.voiceai.databinding.FragmentHistoryBinding;
import com.atmob.voiceai.utils.BoxingUtil;
import com.atmob.voiceai.utils.LinearEndLessOnScrollListener;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class HistoryFragment extends BaseFragment<FragmentHistoryBinding> {


    private HistoryViewModel historyViewModel;

    private HistoryItemAdapter historyItemAdapter;
    private LinearEndLessOnScrollListener linearEndLessOnScrollListener;


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initObserver();
    }

    private void initView() {
        historyItemAdapter = new HistoryItemAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rvHistory.setLayoutManager(linearLayoutManager);
        binding.rvHistory.setAdapter(historyItemAdapter);
        historyItemAdapter.setActionHandler(cloneHistoryBean -> historyViewModel.onHistoryItemClick(cloneHistoryBean));
        linearEndLessOnScrollListener = new LinearEndLessOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                historyViewModel.refreshHistoryList(currentPage);
            }
        };
        binding.rvHistory.addOnScrollListener(linearEndLessOnScrollListener);
        binding.swipeHistoryLayout.setOnRefreshListener(() -> {
            linearEndLessOnScrollListener.reset();
            historyViewModel.refreshHistoryList(1);
        });
    }

    private void initObserver() {
        historyViewModel.getVoiceHistoryList().observe(getViewLifecycleOwner(), list -> historyItemAdapter.submitList(list, () -> {
            if (historyViewModel.isSmoothScrollToTop()) {
                binding.rvHistory.scrollToPosition(0);
            }

        }));
        historyViewModel.getRefreshing().observe(getViewLifecycleOwner(), refreshing -> {
            if (!BoxingUtil.boxing(refreshing)) {
                binding.swipeHistoryLayout.setRefreshing(false);
            }
        });
    }

    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        super.configImmersion(immersionBar);
        immersionBar.statusBarDarkFont(false);
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        historyViewModel = getViewModelProvider().get(HistoryViewModel.class);
        binding.setHistoryViewModel(historyViewModel);
    }
}
