package meerkat.voting.gui.configuration;

import javafx.embed.swing.SwingFXUtils;
import meerkat.protobuf.BallotQuestionUiElement;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * Created by Vladimir Eliezer Tokarev on 10/1/2016.
 * This object contains all the questions and configurations needed for the voting-booth-gui work
 */
public class VotingBoothConfiguration {
    public BallotQuestionUiElement.BallotQuestionUIElement NameSelectionQuestion;
    public BallotQuestionUiElement.BallotQuestionUIElement NameSelectionByPictureQuestion;

    /**
     * Checks that the configuration that have been given is valud
     * @return true if the configuration was valid else false
     */
    public boolean IsConfigurationValid(){
        // check that both the ballot questions really exists
        if (this.NameSelectionByPictureQuestion == null || this.NameSelectionQuestion == null) {
            return false;
        }
        // check that both the questions answers exists
        if (this.NameSelectionQuestion.getAnswers().getAnswers().getAnswersList() == null ||
                this.NameSelectionByPictureQuestion.getAnswers().getAnswers().getAnswersList() == null) {
            return false;
        }
        // check that both the types of the questions answers are supported
        if (BallotQuestionUiElement.ValueType.forNumber(NameSelectionByPictureQuestion.getAnswers().getAnswersType()) == null ||
                BallotQuestionUiElement.ValueType.forNumber(NameSelectionQuestion.getAnswers().getAnswersType()) == null ){
            return false;
        }
        // Check that all the given answers are valid bte strings that can be converted into strings
        for (BallotQuestionUiElement.UIAnswer answer: NameSelectionQuestion.getAnswers().getAnswers().getAnswersList()){
            try {
                answer.getAnswer().toStringUtf8();
                if (answer.getDescription() == null) {
                    return false;
                }
            } catch (Exception e){
                return false;
            }
        }
        // Check that all given byteStrings that are pictures can be converted into pictures
        for (BallotQuestionUiElement.UIAnswer answer :NameSelectionByPictureQuestion.getAnswers().getAnswers().getAnswersList()){
            try {
                BufferedImage bufferedImage = ImageIO.read(answer.getAnswer().newInput());
                SwingFXUtils.toFXImage(bufferedImage, null);
                if (answer.getDescription() == null){
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }

        return true;
    }

}

