package meerkat.bulletinboard.workers.multiserver;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.FutureCallback;
import meerkat.bulletinboard.MultiServerWorker;
import meerkat.bulletinboard.SingleServerBulletinBoardClient;
import meerkat.comm.CommunicationException;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Arbel Deutsch Peled on 27-Dec-15.
 */
public abstract class MultiServerGenericPostWorker<T> extends MultiServerWorker<T, Boolean> {

    public MultiServerGenericPostWorker(List<SingleServerBulletinBoardClient> clients,
                                        int minServers, T payload, int maxRetry,
                                        FutureCallback<Boolean> futureCallback) {

        super(clients, minServers, payload, maxRetry, futureCallback);

    }

    protected abstract void doPost(SingleServerBulletinBoardClient client, T payload);

    /**
     * This method carries out the actual communication with the servers via HTTP Post
     * It accesses the servers one by one and tries to post the payload to each in turn
     * The method will only iterate once through the server list
     * Successful post to a server results in removing the server from the list
     */
    public void run() {

        // Iterate through servers
        for (SingleServerBulletinBoardClient client : clients) {

            // Send request to Server
            doPost(client, payload);

        }

    }

    @Override
    public void onSuccess(Boolean result) {
        if (result){
            if (minServers.decrementAndGet() <= 0){
                succeed(Boolean.TRUE);
            }
        }
    }

    @Override
    public void onFailure(Throwable t) {
        if (maxFailedServers.decrementAndGet() < 0){
            fail(t);
        }
    }
}
