package org.motechproject.dao;

import org.ektorp.BulkDeleteDocument;
import org.ektorp.CouchDbConnector;
import org.ektorp.ViewQuery;
import org.ektorp.support.CouchDbRepositorySupport;
import org.motechproject.model.MotechBaseDataObject;

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

public abstract class MotechBaseRepository<T extends MotechBaseDataObject> extends CouchDbRepositorySupport<T> {
    private Class<T> type;

    protected MotechBaseRepository(Class<T> type, CouchDbConnector db) {
        super(type, db);
        this.type = type;
        initStandardDesignDocument();
    }

    protected void addOrReplace(T entity, String businessFieldName, String businessId) {
        List<T> entities = entities(businessFieldName, businessId);
        if (entities.size() == 0) add(entity);
        else if (entities.size() == 1) update(entity);
        else throw new BusinessIdNotUniqueException(businessFieldName, businessId);
    }

    private List<T> entities(String businessFieldName, String businessId) {
        String viewName = String.format("findBy%s", businessFieldName);
        ViewQuery q = createQuery(viewName).key(businessId).includeDocs(true);
        return db.queryView(q, type);
    }

    public void removeAll(String fieldName, String value) {
        List<T> entities = entities(fieldName, value);
        removeAll(entities);
    }

    private void removeAll(List<T> entities) {
        List<BulkDeleteDocument> bulkDeleteQueue = new ArrayList(entities.size());
        for (T entity : entities) {
            bulkDeleteQueue.add(BulkDeleteDocument.of(entity));
        }
        db.executeBulk(bulkDeleteQueue);
    }

    public void removeAll() {
        removeAll(getAll());
    }

    public void safeRemove(T entity) {
        if (contains(entity.getId()))
            remove(entity);
    }

    protected List<T> getAll(int limit) {
        ViewQuery q = createQuery("all").limit(limit).includeDocs(true);
        return db.queryView(q, type);
    }
}

@@ -31,47 +31,8 @@
 %0D%0A%0D%0A
-import org.ektorp.BulkDeleteDocument;%0D%0A
 impo
@@ -207,37 +207,8 @@
 %0D%0A%0D%0A
-import java.util.ArrayList;%0D%0A
 impo
@@ -1399,182 +1399,63 @@
     
-List%3CBulkDeleteDocument%3E bulkDeleteQueue = new ArrayList(entities.size());%0D%0A        for (T entity : entities) %7B%0D%0A            bulkDeleteQueue.add(BulkDeleteDocument.of
+for (T entity : entities) %7B%0D%0A            remove
 (entity)
 );%0D%0A
@@ -1450,17 +1450,16 @@
 (entity)
-)
 ;%0D%0A     
@@ -1468,50 +1468,8 @@
  %7D%0D%0A
-        db.executeBulk(bulkDeleteQueue);%0D%0A
     

Revert " Priyanka, Raja | #982 | Making removeAll to use bulk delete."