package meerkat.voting.gui;

import com.google.common.util.concurrent.FutureCallback;
import meerkat.pollingstation.PollingStationScanner;
import meerkat.pollingstation.PollingStationWebScanner;
import meerkat.protobuf.PollingStation;

import java.util.concurrent.Semaphore;

/**
 * Created by Laura on 2/1/2017.
 */
public class PollingStationServerToyRun {

    private PollingStationScanner.Consumer scanner;
    private static final String ADDRESS = "http://localhost";
    private static final String SUB_ADDRESS = "";
    private static final int PORT = 8080;

    private Semaphore semaphore;
    private Throwable thrown;
    private boolean dataIsAsExpected;

    private class ScanHandler implements FutureCallback<PollingStation.ScannedData> {

        private final PollingStation.ScannedData expectedData;

        public ScanHandler(PollingStation.ScannedData expectedData) {
            this.expectedData = expectedData;
        }

        @Override
        public void onSuccess(PollingStation.ScannedData result) {
            dataIsAsExpected = result.getChannel().equals(expectedData.getChannel());
            semaphore.release();
        }

        @Override
        public void onFailure(Throwable t) {
            dataIsAsExpected = false;
            thrown = t;
            semaphore.release();
        }
    }

    private class ErrorHandler implements FutureCallback<PollingStation.ScannedData> {

        private final String expectedErrorMessage;

        public ErrorHandler(String expectedErrorMessage) {
            this.expectedErrorMessage = expectedErrorMessage;
        }

        @Override
        public void onSuccess(PollingStation.ScannedData result) {
            dataIsAsExpected = false;
            semaphore.release();
        }

        @Override
        public void onFailure(Throwable t) {
            dataIsAsExpected = t.getMessage().equals(expectedErrorMessage);
            semaphore.release();
        }
    }

    public void init() {

        System.err.println("Setting up Scanner WebApp!");

        scanner = new PollingStationWebScanner(PORT, SUB_ADDRESS);

        semaphore = new Semaphore(0);
        thrown = null;

        try {
            scanner.start();
        } catch (Exception e) {
            System.out.println("Could not start server: " + e.getMessage());
        }

    }

    public static void main(String [] args) {
        PollingStationServerToyRun run = new PollingStationServerToyRun();
        run.init();
    }
}