package meerkat.bulletinboard.workers.singleserver;

import com.google.protobuf.BoolValue;
import meerkat.bulletinboard.SingleServerWorker;
import meerkat.comm.CommunicationException;
import meerkat.protobuf.Comm.*;
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.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 SingleServerGenericPostWorker<T> extends SingleServerWorker<T, Boolean> {

    private final String subPath;

    public SingleServerGenericPostWorker(String serverAddress, String subPath, T payload, int maxRetry) {
        super(serverAddress, payload, maxRetry);
        this.subPath = subPath;
    }

    /**
     * This method carries out the actual communication with the server via HTTP Post
     * It accesses the server and tries to post the payload to it
     * Successful post to a server results
     * @return TRUE if the operation is successful
     * @throws CommunicationException if the operation is unsuccessful
     */
    public Boolean call() throws CommunicationException{

        Client client = clientLocal.get();

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

        try {

            // If a BoolValue entity is returned: the post was successful
            response.readEntity(BoolValue.class);
            return Boolean.TRUE;

        } catch (ProcessingException | IllegalStateException e) {

            // Post to this server failed
            throw new CommunicationException("Could not contact the server");

        }
        finally {
            response.close();
        }

    }

}
