package meerkat.pollingstation;

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

import com.google.protobuf.BoolValue;
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 static meerkat.pollingstation.PollingStationConstants.POLLING_STATION_WEB_SCANNER_CONNECT_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 PollingStationScanner.ScannerClient}
 * This class depends on {@link meerkat.pollingstation.PollingStationWebScanner} and works in conjunction with it
 */
@Path("/")
public class PollingStationScannerWebApp implements PollingStationScanner.PollingStationWebAPI {
    @Context
    ServletContext servletContext;

    final static BoolValue trueValue = BoolValue.newBuilder().setValue(true).build();
    final static BoolValue falseValue = BoolValue.newBuilder().setValue(false).build();

    PollingStationWebScanner.ScanRequestHandler requestHandler;


    /**
     * 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.SCAN_HANDLER_ATTRIBUTE_NAME);

        try {
            requestHandler = (PollingStationWebScanner.ScanRequestHandler) 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 requestHandler.handleConnection(clientData) ? trueValue : falseValue;
    }

    @POST
    @Path(POLLING_STATION_WEB_SCANNER_SCAN_PATH)
    @Consumes(MEDIATYPE_PROTOBUF)
    @Produces(MEDIATYPE_PROTOBUF)
    @Override
    public BoolValue newScan(PollingStation.SignedScannedData scannerData) {
        return requestHandler.handleRequest(scannerData) ? trueValue : falseValue;
    }

}
