package com.ar.artraceartpro.data.repository;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;

import com.ar.artraceartpro.data.local.dao.ImageDataDao;
import com.ar.artraceartpro.data.local.database.AppDatabase;
import com.ar.artraceartpro.data.local.entity.ImageData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class ImageRepository {

    private final ImageDataDao dao;

    public ImageRepository(Context context) {
        AppDatabase appDatabase = AppDatabase.getInstance(context);
        dao = appDatabase.imageDataDao();
    }

    public void insertAll(List<ImageData> imageDataList) {
        new Thread(() -> dao.insertAll(imageDataList)).start();
    }

    public LiveData<List<ImageData>> getFirstCategory(List<String> categories) {
        MediatorLiveData<List<ImageData>> result = new MediatorLiveData<>();
        int totalQueries = categories.size();

        Map<Integer, ImageData> queryResultsMap = new HashMap<>();
        AtomicInteger remainingQueries = new AtomicInteger(totalQueries);

        for (int i = 0; i < totalQueries; i++) {
            String category = categories.get(i);

            LiveData<ImageData> categoryLiveData = dao.getFirstCategory(category);

            int finalI = i;
            result.addSource(categoryLiveData, imageData -> {
                if (imageData != null) {
                    queryResultsMap.put(finalI, imageData);
                }

                if (remainingQueries.decrementAndGet() == 0) {
                    List<ImageData> orderedResults = new ArrayList<>();
                    for (int j = 0; j < totalQueries; j++) {
                        if (queryResultsMap.containsKey(j)) {
                            orderedResults.add(queryResultsMap.get(j));
                        }
                    }

                    result.setValue(orderedResults);
                }
            });
        }

        return result;
    }

    public LiveData<List<ImageData>> getRecommend(String name, int index) {
        return dao.getImageByIndex(name, index);
    }

    public LiveData<List<ImageData>> getAllFavorite() {
        return dao.getAllFavorite();
    }

    public LiveData<List<ImageData>> getAllImportLive() {
        return dao.getAllImportLive();
    }

    public void insert(ImageData imageData) {
        dao.insert(imageData);
    }

    public List<ImageData> getAllImport() {
        return dao.getAllImport();
    }

    public LiveData<List<ImageData>> getAllCategory(String name) {
        return dao.getAllCategory(name);
    }

}
