package meerkat.bulletinboard.workers.singleserver;

import com.google.protobuf.Int64Value;
import meerkat.bulletinboard.SingleServerWorker;
import meerkat.comm.CommunicationException;
import meerkat.protobuf.BulletinBoardApi.BeginBatchMessage;
import meerkat.rest.Constants;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import static meerkat.bulletinboard.BulletinBoardConstants.BEGIN_BATCH_PATH;
import static meerkat.bulletinboard.BulletinBoardConstants.BULLETIN_BOARD_SERVER_PATH;

/**
 * Created by Arbel Deutsch Peled on 27-Dec-15.
 * Tries to contact server once and perform a post operation
 */
public class SingleServerBeginBatchWorker extends SingleServerWorker<BeginBatchMessage,Int64Value> {

    public SingleServerBeginBatchWorker(String serverAddress, BeginBatchMessage payload, int maxRetry) {
        super(serverAddress, payload, maxRetry);
    }

    @Override
    public Int64Value call() throws Exception {
        Client client = clientLocal.get();

        WebTarget webTarget = client.target(serverAddress).path(BULLETIN_BOARD_SERVER_PATH).path(BEGIN_BATCH_PATH);
        Response response = webTarget.request(Constants.MEDIATYPE_PROTOBUF).post(
                Entity.entity(payload, Constants.MEDIATYPE_PROTOBUF));

        try {

            Int64Value result =  response.readEntity(Int64Value.class);
            return result;

        } catch (ProcessingException | IllegalStateException e) {

            // Post to this server failed
            throw new CommunicationException("Could not contact the server. Original error: " + e.getMessage());

        } catch (Exception e) {
            throw new CommunicationException("Could not contact the server. Original error: " + e.getMessage());
        }
        finally {
            response.close();
        }
    }
}
