package com.datarecovery.master.module.example;

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

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

import com.atmob.analytics.utils.Maps;
import com.atmob.app.lib.base.BaseFragment;
import com.atmob.common.data.KVUtils;
import com.datarecovery.master.data.api.bean.ExampleBean;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.databinding.FragmentExampleBinding;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.browser.BrowserActivity;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class ExampleFragment extends BaseFragment<FragmentExampleBinding> {


    private ExampleViewModel exampleViewModel;
    private ExampleAdapter exampleAdapter;
    private boolean goToDetail;

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

    private void initView() {
        exampleAdapter = new ExampleAdapter(this);
        binding.ryExample.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.ryExample.setAdapter(exampleAdapter);
        exampleAdapter.setOnItemClickListener(itemBean -> {
            boolean isFirstClickCase = KVUtils.getDefault().getBoolean("is_first_click_case", true);
            if (isFirstClickCase) {
                KVUtils.getDefault().putBoolean("is_first_click_case", false);
            }
            List<ExampleBean> exampleBeans = exampleViewModel.getExampleList().getValue();
            EventHelper.report(EventId.EVENT_3010100, Maps.of(
                    "case_id", exampleBeans == null ? 0 : exampleBeans.indexOf(itemBean) + 1,
                    "is_first_click_case", isFirstClickCase
            ));
            goToDetail = true;
            BrowserActivity.start(getActivity(), itemBean.getLink());
            EventHelper.report(EventId.EVENT_3010200);
        });
    }

    private void initObserver() {
        exampleViewModel.getExampleList().observe(getViewLifecycleOwner(), list -> exampleAdapter.submit(list));
    }

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

    @Override
    protected void initViewModel() {
        super.initViewModel();
        exampleViewModel = getViewModelProvider().get(ExampleViewModel.class);
        binding.setExampleViewModel(exampleViewModel);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (goToDetail) {
            goToDetail = false;
            EventHelper.report(EventId.EVENT_3010201);
        }
    }
}
