/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.au.services.domain.model.authentication;

import org.apache.commons.codec.binary.Base64;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.ov.commons.random.RandomType;
import com.scytl.products.ov.commons.random.impl.SecureRandomBytes;
import com.scytl.products.ov.commons.random.impl.SecureRandomInteger;
import com.scytl.products.ov.commons.random.impl.SecureRandomString;

/**
 * Class representing a challenge.
 */
public final class Challenge {

	// String representing the challenge value
	private String challengeValue;

	/**
	 * Builds a new challenge object for a given type and length.
	 * 
	 * @param randomType - type of the random generated value.
	 * @param length - length of the random generated value.
	 * @return challenge containing a random value.
	 * @throws GeneralCryptoLibException if length is out of the range for this generator.
	 */
	public Challenge(RandomType randomType, int length) throws GeneralCryptoLibException {
		switch (randomType) {
		case BYTES:
			// byte array is converted to string using apache commons encoding. 
			// To decode, use utility Base64.decodeBase64(base64String)
			setChallengeValue(Base64.encodeBase64String(SecureRandomBytes.getInstance().getRandomValue(length)));
			break;
		case STRING:
			setChallengeValue(SecureRandomString.getInstance().getRandomValue(length));
			break;
		case INTEGER:
			setChallengeValue(String.valueOf(SecureRandomInteger.getInstance().getRandomValue(length)));
			break;
		}
	}

	// sets the value of the field challengeValue.
	private void setChallengeValue(String challengeValue) {
		this.challengeValue = challengeValue;
	}

	/**
	 * Returns the current value of the field challengeValue.
	 *
	 * @return Returns the challengeValue.
	 */
	public String getChallengeValue() {
		return challengeValue;
	}
}
