package ab.issue.db;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Transaction;

import java.util.Collection;
import java.util.List;

import ab.issue.model.Barcode;
import app.issue.commons.sqlite.room.IDao;

import static ab.issue.db.DbConstants.*;

@SuppressWarnings("Guava")
@Dao
public abstract class BarcodeDao implements IDao<Barcode> {

    final BarcodeDatabase barcodeDatabase;

    BarcodeDao(BarcodeDatabase barcodeDatabase) {
        this.barcodeDatabase = barcodeDatabase;
    }

    @Query("SELECT DISTINCT " + COLUMN_NAME_IMAGE_PATH + " FROM " + BARCODE_TABLE_NAME)
    public abstract List<String> getAllImagesPath();

    @Transaction
    public List<Barcode> insertBarcodes(List<Barcode> barcodes) {
        insertWithId(barcodes);
        saveBarcodeFormat(barcodes);
        return barcodes;
    }

    public int update(Barcode barcode, boolean favorite) {
        barcode.setFavorite(favorite);
        return update(barcode);
    }

    public int update(List<Barcode> barcodes, String path, String notes, boolean isFavorite) {
        for (Barcode barcode : barcodes) {
            barcode.setImagePath(path);
            barcode.setNotes(notes);
            barcode.setFavorite(isFavorite);
        }
        return update(barcodes);
    }

    private void insertWithId(Collection<Barcode> barcodes) {
        long[] ids = insert(barcodes);
        int i = 0;
        for (Barcode barcode : barcodes) {
            barcode.setId(ids[i++]);
        }
    }

    private void saveBarcodeFormat(Collection<Barcode> barcodes) {
        for (Barcode barcode : barcodes) {
            barcode.getFormat().getValue().setBarcodeId(barcode.getId());
            barcode.getFormat().getValue().save(barcodeDatabase);
        }
    }
}
