package meerkat.pollingstation;

import com.google.protobuf.BoolValue;
import meerkat.protobuf.Crypto;
import meerkat.protobuf.PollingStation;
import meerkat.rest.Constants;
import meerkat.rest.ProtobufMessageBodyReader;
import meerkat.rest.ProtobufMessageBodyWriter;

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

/**
 * Created by Laura on 3/20/2017.
 */
public class ScannerClientAPI implements PollingStationScanner.Producer {
    private Client client;
    private WebTarget webTarget;

    public ScannerClientAPI(String url) {
        client = ClientBuilder.newClient();
        client.register(ProtobufMessageBodyReader.class);
        client.register(ProtobufMessageBodyWriter.class);
        webTarget = client.target(url);
    }


    /**
     * Sends the scanned data to the polling station server
     * @param scannedData
     * @return boolean value: true if the data was sent successfully, false otherwise
     */
    @Override
    public BoolValue newScan(PollingStation.ScannedData scannedData) {

        Response response = webTarget.request(Constants.MEDIATYPE_PROTOBUF).post(Entity.entity(scannedData, Constants.MEDIATYPE_PROTOBUF),
                );
        BoolValue res = response.readEntity(BoolValue.class);
        response.close();
        return res.getValue();
    }


    public void close() {
        client.close();

    }

    @Override
    public BoolValue connect(PollingStation.ConnectionClientData clientData) {
        return null;
    }

        return null;
    }

    @Override
    public BoolValue reportScanError(PollingStation.ErrorMsg errorMsg, Crypto.Signature errorMsgSignature) {
        return null;
    }
}
