package ab.issue.db;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Transaction;
import android.support.annotation.Nullable;

import com.google.common.collect.FluentIterable;

import java.util.ArrayList;
import java.util.List;

import ab.issue.db.model.BarcodeHistoryEntity;
import ab.issue.model.Barcode;
import timber.log.Timber;

import static ab.issue.db.DbConstants.BARCODE_TABLE_NAME;
import static ab.issue.db.DbConstants.COLUMN_NAME_BARCODE_ID;
import static ab.issue.db.DbConstants.COLUMN_NAME_FAVORITE;

@SuppressWarnings("Guava")
@Dao
public abstract class HistoryDao {

    @Transaction
    @Query("SELECT * FROM " + BARCODE_TABLE_NAME)
    abstract List<BarcodeHistoryEntity> getAll();

    @Transaction
    @Query("SELECT * FROM " + BARCODE_TABLE_NAME + " WHERE " + COLUMN_NAME_BARCODE_ID + "= :id")
    abstract BarcodeHistoryEntity findById(long id);

    @Transaction
    @Query("SELECT * FROM " + BARCODE_TABLE_NAME + " WHERE " + COLUMN_NAME_FAVORITE + " = 1")
    public abstract List<BarcodeHistoryEntity> getFavorites();

    @Transaction
    @Query("SELECT * FROM " + BARCODE_TABLE_NAME + " WHERE " + COLUMN_NAME_BARCODE_ID + " IN (:barcodeIds)")
    abstract List<BarcodeHistoryEntity> findBarcodesByIds(List<Long> barcodeIds);

    public List<Barcode> getFavoriteBarcodes() {
        return FluentIterable.from(getFavorites())
                .transform(BarcodeHistoryEntity::fillValue)
                .toList();
    }

    @Nullable
    public Barcode findBarcode(long id) {
        BarcodeHistoryEntity entry = findById(id);
        if (entry == null) {
            return null;
        }
        entry.fillValue();
        return entry.barcode;
    }

    public List<Barcode> getHistory() {
        List<Barcode> history = toBarcodes(getAll());
        Timber.d("history=%s", history);
        return history;
    }

    public List<Barcode> findBarcodes(List<Long> barcodeIds) {
        List<Barcode> result = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(barcodeIds)) {
//            result = toBarcodes(findBarcodesByIds(barcodeIds));
//        }
        return result;
    }

    private List<Barcode> toBarcodes(Iterable<BarcodeHistoryEntity> barcodeEntries) {
        return FluentIterable.from(barcodeEntries)
                .transform(BarcodeHistoryEntity::fillValue)
                .toList();
    }
}
