package it.integry.integrywmsnative.core.data_store.db.repository.implementations;

import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.core.data_store.db.dao.GrigliaDao;
import it.integry.integrywmsnative.core.data_store.db.entity.Griglia;
import it.integry.integrywmsnative.core.data_store.db.repository.GrigliaRepository;
import it.integry.integrywmsnative.core.data_store.db.wrappers.GrigliaWrapper;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;

public class GrigliaDataSource extends Repository implements GrigliaRepository {

    private final GrigliaDao mGrigliaDao;

    @Inject
    public GrigliaDataSource(GrigliaDao grigliaDao) {
        this.mGrigliaDao = grigliaDao;
    }

    public void selectAll(RunnableArgs<List<Griglia>> onSuccess, RunnableArgs<Exception> onError) {
        Runnable query = () -> {
            try {
                onSuccess.run(mGrigliaDao.getAll());
            } catch (Exception e) {
                onError.run(e);
            }
        };
        execute(query);
    }

    public void findByCodAlis(String codAlis, RunnableArgs<GrigliaWrapper> onSuccess, RunnableArgs<Exception> onError) {
        Runnable query = () -> {
            try {
                onSuccess.run(mGrigliaDao.findByCodAlis(codAlis));
            } catch (Exception e) {
                onError.run(e);
            }
        };
        execute(query);
    }


    public void saveGriglia(Griglia griglia, RunnableArgs<Integer> onSuccess, RunnableArgs<Exception> onFail) {
        execute(() -> {
            try {
                if (griglia.getGrigliaId() <= 0) {
                    griglia.setGrigliaId((int) mGrigliaDao.insert(griglia));
                } else {
                    mGrigliaDao.update(griglia);
                }
                onSuccess.run(griglia.getGrigliaId());
            } catch (Exception e) {
                onFail.run(e);
            }
        });
    }

    public void findGrigliaById(int idGriglia, RunnableArgs<Griglia> onLoad, RunnableArgs<Exception> onFail) {
        execute(() -> {
            try {
                onLoad.run(mGrigliaDao.findGrigliaById(idGriglia));
            } catch (Exception e) {
                onFail.run(e);
            }
        });
    }
}
