package ab.issue.db;

import org.joda.time.DateTime;

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

import javax.inject.Inject;

import ab.issue.model.Barcode;

public class UpdateTimeOnUpsertBarcodeDao extends BarcodeDao {

    @Inject
    UpdateTimeOnUpsertBarcodeDao(BarcodeDatabase barcodeDatabase) {
        super(barcodeDatabase);
    }

    @Override
    public List<String> getAllImagesPath() {
        return barcodeDatabase.barcodeDao().getAllImagesPath();
    }

    @Override
    public List<Barcode> insertBarcodes(List<Barcode> barcodes) {
        updateTimeForInsert(barcodes);
        return barcodeDatabase.barcodeDao().insertBarcodes(barcodes);
    }

    @Override
    public int update(Barcode barcode, boolean favorite) {
        updateTimeForUpdate(Collections.singleton(barcode));
        return barcodeDatabase.barcodeDao().update(barcode, favorite);
    }

    @Override
    public long insert(Barcode row) {
        throw new UnsupportedOperationException("Use insertBarcodes()");
    }

    @Override
    public long[] insert(Collection<Barcode> rows) {
        throw new UnsupportedOperationException("Use insertBarcodes()");
    }

    @Override
    public int update(Barcode barcode) {
        updateTimeForUpdate(Collections.singleton(barcode));
        return barcodeDatabase.barcodeDao().update(barcode);
    }

    @Override
    public int update(Collection<Barcode> barcodes) {
        updateTimeForUpdate(barcodes);
        return barcodeDatabase.barcodeDao().update(barcodes);
    }

    @Override
    public void delete(Barcode barcode) {
        barcodeDatabase.barcodeDao().delete(barcode);
    }

    @Override
    public void delete(Barcode[] rows) {
        barcodeDatabase.barcodeDao().delete(rows);
    }

    @Override
    public void delete(Collection<Barcode> rows) {
        barcodeDatabase.barcodeDao().delete(rows);
    }

    private void updateTimeForInsert(Collection<Barcode> barcodes) {
        for (Barcode barcode : barcodes) {
            barcode.setLastUpdated(new DateTime());
            barcode.setCreateTime(new DateTime());
        }
    }

    private void updateTimeForUpdate(Collection<Barcode> barcodes) {
        for (Barcode barcode : barcodes) {
            barcode.setLastUpdated(new DateTime());
        }
    }
}
