package meerkat.pollingstation;

/**
 * Created by Arbel on 5/31/2016.
 */

import com.google.common.util.concurrent.FutureCallback;
import com.google.protobuf.BoolValue;
import meerkat.protobuf.Crypto;
import meerkat.protobuf.PollingStation;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import java.io.IOException;

import static meerkat.pollingstation.PollingStationConstants.POLLING_STATION_WEB_SCANNER_CONNECT_PATH;
import static meerkat.pollingstation.PollingStationConstants.POLLING_STATION_WEB_SCANNER_ERROR_PATH;
import static meerkat.pollingstation.PollingStationConstants.POLLING_STATION_WEB_SCANNER_SCAN_PATH;
import static meerkat.rest.Constants.MEDIATYPE_PROTOBUF;

/**
 * Implements a Web-App interface for {@link meerkat.pollingstation.PollingStationScanner.Producer}
 * This class depends on {@link meerkat.pollingstation.PollingStationWebScanner} and works in conjunction with it
 */
@Path("/")
public class PollingStationScannerWebApp implements PollingStationScanner.Producer {

    @Context
    ServletContext servletContext;

    Iterable<FutureCallback<PollingStation.ScannedData>> callbacks;

    /**
     * This method is called by the Jetty engine when instantiating the servlet
     */
    @PostConstruct
    @SuppressWarnings("unchecked")
    public void init() throws Exception {
        Object context = servletContext.getAttribute(PollingStationWebScanner.CALLBACKS_ATTRIBUTE_NAME);

        try {
            callbacks = (Iterable<FutureCallback<PollingStation.ScannedData>>) context;
        } catch (ClassCastException e) {
            throw e;
        }

    }

    @POST
    @Path(POLLING_STATION_WEB_SCANNER_CONNECT_PATH)
    @Consumes(MEDIATYPE_PROTOBUF)
    @Produces(MEDIATYPE_PROTOBUF)
    @Override
    public BoolValue connect(PollingStation.ConnectionClientData clientData) {
        return null;
    }

    @POST
    @Path(POLLING_STATION_WEB_SCANNER_SCAN_PATH)
    @Consumes(MEDIATYPE_PROTOBUF)
    @Produces(MEDIATYPE_PROTOBUF)
    @Override
    public BoolValue newScan(PollingStation.ScannedData scannedData) {

        boolean handled = false;

        // TODO:
        for (FutureCallback<PollingStation.ScannedData> callback : callbacks){

            callback.onSuccess(scannedData);
            handled = true;

        }

        return BoolValue.newBuilder()
                .setValue(handled)
                .build();

    }

}
