package meerkat.pollingstation;

import java.security.SecureRandom;
import java.util.List;
import java.util.LinkedList;

import com.google.common.util.concurrent.FutureCallback;
import meerkat.protobuf.PollingStation;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;

import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.server.ResourceConfig;

import meerkat.protobuf.PollingStation.ScannedData;
import meerkat.rest.*;

/**
 * Created by Arbel on 05/05/2016.
 */

public class PollingStationWebScanner implements PollingStationScanner.Consumer {

    public final static String CALLBACKS_ATTRIBUTE_NAME = "controller";

    private final Server server;
    private final List<FutureCallback<ScannedData>> callbacks;
    boolean verifyScanner;
    byte nonce[];

    public PollingStationWebScanner(int port, String contextPath) {

        callbacks = new LinkedList<>();

        server = new Server(port);

        ServletContextHandler servletContextHandler = new ServletContextHandler(server, contextPath);
        servletContextHandler.setAttribute(CALLBACKS_ATTRIBUTE_NAME, (Iterable<FutureCallback<ScannedData>>) callbacks);

        ResourceConfig resourceConfig = new ResourceConfig(PollingStationScannerWebApp.class);
        resourceConfig.register(ProtobufMessageBodyReader.class);
        resourceConfig.register(ProtobufMessageBodyWriter.class);

        ServletHolder servletHolder = new ServletHolder(new ServletContainer(resourceConfig));

        servletContextHandler.addServlet(servletHolder, "/*");
    }



    @Override
    public PollingStation.ConnectionServerData start(boolean verifyScanner) throws Exception {
        this.verifyScanner = verifyScanner;
        nonce = new byte[32];
        new SecureRandom().nextBytes(nonce);


        server.start();
        return null;
    }

    @Override
    public void stop() throws Exception {
        server.stop();
    }

    @Override
    public void subscribe(FutureCallback<ScannedData> scanCallback) {
        callbacks.add(scanCallback);
    }

}
