package meerkat.voting.gui;

import javafx.application.Application;
import javafx.stage.Stage;
import meerkat.protobuf.BallotQuestionUiElement;
import meerkat.voting.gui.configuration.VotingBoothConfiguration;
import meerkat.voting.gui.managment.ChainBuilder;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 * Created by Vladimir Eliezer Tokarev on 8/27/2016.
 * The current voting-booth intialization process is next:
 * Main calls to ChainBuilder which initilizes all the TwoWayNode's
 */
public class Main extends Application {

    private final Logger logger = LoggerFactory.getLogger(Main.class);
    private final String DEFAULT_CONFIGURATION_PATH = "/configuration/configuration.bin";
    /**
     * Creates the VotingBoothConfigurationCreator and creates configuration based on given path
     * @return VotingBoothVonfiguration parsed from json file
     * @throws IOException will be thrown if the configuraiton file doesnt exist
     * @throws JSONException will be thrown if the json is unvalid
     */
    private VotingBoothConfiguration GetConfig() throws IOException, JSONException, URISyntaxException {
        FileInputStream fis = new FileInputStream(getClass().getResource(DEFAULT_CONFIGURATION_PATH).getPath());
        BallotQuestionUiElement.BallotQuestionsUIElements read_questions = BallotQuestionUiElement.BallotQuestionsUIElements.parseFrom(fis);
        VotingBoothConfiguration votingBoothConfiguration = new VotingBoothConfiguration();
        votingBoothConfiguration.NameSelectionQuestion = read_questions.getQuestions(1);
        votingBoothConfiguration.NameSelectionByPictureQuestion = read_questions.getQuestions(0);
        return votingBoothConfiguration;
    }

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        this.logger.debug("Started Meerkat Voting GUI Application");
        ChainBuilder.Build(primaryStage, GetConfig());
        primaryStage.setTitle("Meerkat Polling Station");
        primaryStage.show();
    }

    public static void main(String[] args) throws InterruptedException {
        launch(args);
    }

}

