package com.prank.funnypranksounds.data.repository;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import androidx.lifecycle.LiveData;

import com.prank.funnypranksounds.data.local.dao.AudioDataDao;
import com.prank.funnypranksounds.data.local.database.AppDatabase;
import com.prank.funnypranksounds.data.local.entity.AudioData;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioRepository {

    private final AudioDataDao dao;
    private final ExecutorService executorService;

    public AudioRepository(Context context) {
        AppDatabase appDatabase = AppDatabase.getInstance(context);
        dao = appDatabase.audioDataDao();
        executorService = Executors.newSingleThreadExecutor();
    }

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

    public void insert(AudioData audioData) {
        new Thread(() -> dao.insert(audioData)).start();
    }

    public void update(AudioData audioData) {
        new Thread(() -> dao.update(audioData)).start();
    }

    public LiveData<List<AudioData>> getFirstCategory() {
        return dao.getFirstCategory();
    }

    public LiveData<List<AudioData>> getCategory(String name) {
        return dao.getCategory(name);
    }

    public LiveData<List<AudioData>> getFavorite() {
        return dao.getFavorite();
    }

    public void getCountAsync(String uri, CountCallback callback) {
        executorService.execute(() -> {
            int count = dao.getCount(uri);
            new Handler(Looper.getMainLooper()).post(() -> callback.onCountFetched(count));
        });
    }

    public interface CountCallback {
        void onCountFetched(int count);
    }

    public LiveData<List<AudioData>> getExternal() {
        return dao.getExternal();
    }

    public void delete(AudioData audioData){
        new Thread(() -> dao.delete(audioData)).start();
    }

}
