package com.ar.imagetracear.fragment;

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

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;


import com.ar.imagetracear.databinding.FragmentHomeBinding;
import com.ar.imagetracear.database.AppDatabase;
import com.ar.imagetracear.database.ImageTraceEntry;
import com.ar.imagetracear.adapter.HomeAdapter;
import com.ar.imagetracear.utils.ItemDecoration;
import com.ar.imagetracear.utils.Names;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding viewBinding;
    private final List<String> categoryNames = Names.getAllImage();
    private final List<String> labelNames = new ArrayList<>();
    private HomeAdapter homeListAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewBinding = FragmentHomeBinding.inflate(inflater, container, false);

        prepareLabels();
        initializeGridList();
        fetchAllCategoryThumbnails(categoryNames);

        return viewBinding.getRoot();
    }

    private void prepareLabels() {
        for (String item : categoryNames) {
            if (item.length() > 4) {
                labelNames.add(item.substring(4));
            } else {
                labelNames.add(item);
            }
        }
    }

    private void initializeGridList() {
        viewBinding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 1));
        homeListAdapter = new HomeAdapter(requireActivity(), new ArrayList<>(), categoryNames, labelNames);
        viewBinding.recyclerview.setAdapter(homeListAdapter);
        viewBinding.recyclerview.addItemDecoration(new ItemDecoration(16, 19, 10));
    }

    private void fetchAllCategoryThumbnails(List<String> allCategories) {
        int expectedSize = allCategories.size();
        Map<Integer, List<ImageTraceEntry>> cacheMap = new HashMap<>();

        for (int index = 0; index < expectedSize; index++) {
            final int currentIndex = index;
            String key = allCategories.get(currentIndex);

            AppDatabase.getInstance(requireContext())
                    .imageTraceEntryDao()
                    .getFileByPathLimitOne(key)
                    .observe(getViewLifecycleOwner(), imageList -> {
                        cacheMap.put(currentIndex, imageList);
                        if (cacheMap.size() == expectedSize) {
                            aggregateAndDisplay(cacheMap, expectedSize);
                        }
                    });
        }
    }

    private void aggregateAndDisplay(Map<Integer, List<ImageTraceEntry>> resultData, int count) {
        List<ImageTraceEntry> mergedList = new CopyOnWriteArrayList<>();

        for (int idx = 0; idx < count; idx++) {
            List<ImageTraceEntry> section = resultData.get(idx);
            if (section != null && !section.isEmpty()) {
                mergedList.addAll(section);
            }
        }

        homeListAdapter.updateData(mergedList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewBinding = null;
    }
}