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.OrdineDao;
import it.integry.integrywmsnative.core.data_store.db.entity.Griglia;
import it.integry.integrywmsnative.core.data_store.db.entity.Ordine;
import it.integry.integrywmsnative.core.data_store.db.repository.OrdineRepository;
import it.integry.integrywmsnative.core.data_store.db.view_model.OrdineWithGriglia;
import it.integry.integrywmsnative.core.data_store.db.wrappers.OrdineWrapper;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;

public class OrdineDataSource extends Repository implements OrdineRepository {

    private OrdineDao mOrdineDao;

    @Inject
    public OrdineDataSource(OrdineDao ordineDao) {
        this.mOrdineDao = ordineDao;
    }

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

    public void selectAllTransmitted(RunnableArgs<List<OrdineWithGriglia>> onSuccess, RunnableArgs<Exception> onError) {
        Runnable query = () -> {
            try {
                onSuccess.run(mOrdineDao.getAllTrasnmitted());
            } catch (Exception e) {
                onError.run(e);
            }
        };
        execute(query);
    }

    public void selectAllOpenOrders(Griglia griglia, RunnableArgs<List<OrdineWrapper>> onSuccess, RunnableArgs<Exception> onError) {
        Runnable query = () -> {
            try {
                onSuccess.run(mOrdineDao.getAllOpenOrdersByGriglia(griglia.getGrigliaId()));
            } catch (Exception e) {
                onError.run(e);
            }
        };
        execute(query);
    }

    public void insert(Ordine ordine, RunnableArgs<Integer> onSuccess, RunnableArgs<Exception> onError) {
        execute(() -> {
            try {
                Long id = mOrdineDao.insert(ordine);
                onSuccess.run(id.intValue());
            } catch (Exception e) {
                onError.run(e);
            }
        });
    }


    public void updateOrder(Ordine ordine, RunnableArgs<Ordine> onSuccess, RunnableArgs<Exception> onError) {
        execute(() -> {
            try {
                mOrdineDao.update(ordine);
                onSuccess.run(ordine);
            } catch (Exception e) {
                onError.run(e);
            }
        });
    }

    public void delete(Ordine ordine, Runnable onSuccess, RunnableArgs<Exception> onError) {
        execute(() -> {
            try {
                mOrdineDao.delete(ordine);
                onSuccess.run();
            } catch (Exception e) {
                onError.run(e);
            }
        });
    }
}
