// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package website.quiz;

import java.io.IOException;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Quiz {
    private int maxTries;
    private List<QuizQuestion> questions;
    private int questionIndex;
    private boolean wrong;
    private int numTries;
    private Integer answer;
    public Quiz() {
        questionIndex = 0;
        numTries = 0;
        questions = new ArrayList<QuizQuestion>();
        try {
            Properties prop = new Properties();
            prop.load(getClass().getResourceAsStream("/website/resources/questions.properties"));
            maxTries = Integer.parseInt(prop.getProperty("max.tries"));
            for(int i = 1; ; i++) {
                String q = prop.getProperty("question." + i + ".question");
                String a = prop.getProperty("question." + i + ".answer");
                if(q == null || a == null) break;
                questions.add(new QuizQuestion(q, Integer.parseInt(a)));
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    public int getMaxTries() {
        return maxTries;
    }
    public int getNumQuestions() {
        return questions.size();
    }
    public QuizQuestion getQuestion() {
        return questions.get(questionIndex);
    }
    public int getQuestionIndex() {
        return questionIndex;
    }
    public boolean getWrong() {
        return wrong;
    }
    public Integer getAnswer() {
        return null;
    }
    public void setAnswer(Integer answer) {
        this.answer = answer;
    }
    public String answerQuestion() {
        if(questions.get(questionIndex).getAnswer() == answer.intValue()) {
            questionIndex++;
            if(questionIndex >= questions.size()) {
                return "completed?faces-redirect=true";
            } else {
                wrong = false;
                return "quiz?faces-redirect=true";
            }
        } else {
            numTries++;
            if(numTries >= maxTries) {
                return "failed?faces-redirect=true";
            } else {
                wrong = true;
                return "quiz?faces-redirect=true";
            }
        }
    }
}
