package com.ar.arsketch.fragment;

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

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

import com.ar.arsketch.activity.CameraActivity;
import com.ar.arsketch.activity.CategoryActivity;
import com.ar.arsketch.activity.SettingActivity;
import com.ar.arsketch.adapter.ImageAdapter;
import com.ar.arsketch.databinding.FragmentHomeBinding;
import com.ar.arsketch.room.AppDatabase;
import com.ar.arsketch.room.ImageEntry;
import com.ar.arsketch.topon.AdManager;
import com.ar.arsketch.topon.onActionListener;
import com.ar.arsketch.utils.ItemDecoration;
import com.ar.arsketch.utils.Names;

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

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private ImageAdapter adapter;
    private final List<String> categories = Names.getAllDir();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new ImageAdapter(requireContext(), new ArrayList<>(),requireActivity());
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerView.addItemDecoration(itemDecoration);

    }

    private void initEvent() {

        binding.setting.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), SettingActivity.class);
            requireContext().startActivity(intent);
        });

        binding.sketch.setOnClickListener(v -> {
            AdManager.showTopOn(requireActivity(), new onActionListener() {
                @Override
                public void onAction() {
                    Intent intent = new Intent(requireActivity(), CameraActivity.class);
                    requireContext().startActivity(intent);
                }
            });
        });

        binding.gallery.setOnClickListener(v -> {
            AdManager.showTopOn(requireActivity(), new onActionListener() {
                @Override
                public void onAction() {
                    Intent intent = new Intent(requireActivity(), CategoryActivity.class);
                    requireContext().startActivity(intent);
                }
            });
        });

        loadImages(categories);

    }

    private void loadImages(List<String> categories) {
        Map<Integer, List<ImageEntry>> queryResultsMap = new HashMap<>();
        int totalQueries = categories.size();

        Random random = new Random();
        int index = random.nextInt(10);

        for (int i = 0; i < totalQueries; i++) {
            String original = categories.get(i);
            int finalI = i;
            AppDatabase.getInstance(requireContext())
                    .imageEntryDao()
                    .getImageByCategoryAndIndexLive(original, index)
                    .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                        @Override
                        public void onChanged(List<ImageEntry> imageEntries) {
                            queryResultsMap.put(finalI, imageEntries);
                            if (queryResultsMap.size() == totalQueries) {
                                List<ImageEntry> allImageEntries = new CopyOnWriteArrayList<>();
                                for (int j = 0; j < totalQueries; j++) {
                                    List<ImageEntry> currentEntries = queryResultsMap.get(j);
                                    if (currentEntries != null) {
                                        allImageEntries.addAll(currentEntries);
                                    }
                                }
                                adapter.updateData(allImageEntries);
                            }
                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}