package com.grigowashere.aismap.data;

import android.content.Context;

import androidx.lifecycle.LiveData;

import com.grigowashere.aismap.data.dao.AISVesselDao;
import com.grigowashere.aismap.data.dao.VesselDao;
import com.grigowashere.aismap.data.entity.AISVesselEntity;
import com.grigowashere.aismap.data.entity.VesselEntity;

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

public class Repository {
    private final AISVesselDao aisVesselDao;
    private final VesselDao vesselDao;
    private final ExecutorService ioExecutor = Executors.newSingleThreadExecutor();

    public Repository(Context context) {
        AppDatabase db = AppDatabase.getInstance(context);
        this.aisVesselDao = db.aisVesselDao();
        this.vesselDao = db.vesselDao();
    }

    public void upsertAIS(AISVesselEntity entity) {
        ioExecutor.execute(() -> aisVesselDao.upsert(entity));
    }

    public void deleteStaleAIS(long thresholdEpochMs) {
        ioExecutor.execute(() -> aisVesselDao.deleteStale(thresholdEpochMs));
    }

    public List<AISVesselEntity> getAllAISSync() {
        return aisVesselDao.getAll();
    }

    public LiveData<List<AISVesselEntity>> observeAllAIS() {
        return aisVesselDao.observeAll();
    }

    public AISVesselEntity getAISByMmsiSync(String mmsi) {
        return aisVesselDao.getByMmsi(mmsi);
    }

    public void upsertOwnVessel(VesselEntity entity) {
        ioExecutor.execute(() -> {
            vesselDao.upsert(entity);
        });
    }

    public VesselEntity getLatestOwnVesselSync() {
        return vesselDao.getLatest();
    }
}


