package meerkat.bulletinboard.workers.singleserver;

import meerkat.bulletinboard.SingleServerWorker;
import meerkat.comm.CommunicationException;
import meerkat.protobuf.BulletinBoardApi.SyncQuery;
import meerkat.protobuf.BulletinBoardApi.SyncQueryResponse;
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;
import static meerkat.bulletinboard.BulletinBoardConstants.SYNC_QUERY_PATH;

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

    public SingleServerQuerySyncWorker(String serverAddress, SyncQuery payload, int maxRetry) {
        super(serverAddress, payload, maxRetry);
    }

    @Override
    public SyncQueryResponse call() throws Exception {

        Client client = clientLocal.get();

        WebTarget webTarget;
        Response response;

        // Send request to Server

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

        // Retrieve answer

        try {

            // If a BulletinBoardMessageList is returned: the read was successful
            return response.readEntity(SyncQueryResponse.class);

        } catch (ProcessingException | IllegalStateException e) {

            // Read failed
            throw new CommunicationException("Server access failed");

        }
        finally {
            response.close();
        }

    }
}
