package meerkat.bulletinboard.workers.singleserver;

import com.google.protobuf.Int64Value;
import meerkat.bulletinboard.SingleServerWorker;
import meerkat.comm.CommunicationException;
import meerkat.protobuf.BulletinBoardApi.SyncQuery;
import meerkat.protobuf.BulletinBoardApi.GenerateSyncQueryParams;
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.GENERATE_SYNC_QUERY_PATH;

/**
 * Created by Arbel Deutsch Peled on 27-Dec-15.
 * Tries to contact server once and perform a Sync Query Generation operation
 */
public class SingleServerGenerateSyncQueryWorker extends SingleServerWorker<GenerateSyncQueryParams,SyncQuery> {

    public SingleServerGenerateSyncQueryWorker(String serverAddress, GenerateSyncQueryParams payload, int maxRetry) {
        super(serverAddress, payload, maxRetry);
    }

    @Override
    public SyncQuery call() throws Exception {

        Client client = clientLocal.get();

        WebTarget webTarget = client.target(serverAddress).path(BULLETIN_BOARD_SERVER_PATH).path(GENERATE_SYNC_QUERY_PATH);

        Response response = webTarget.request(Constants.MEDIATYPE_PROTOBUF).post(Entity.entity(payload, Constants.MEDIATYPE_PROTOBUF));

        try {

            SyncQuery result = response.readEntity(SyncQuery.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();
        }
    }
}
