package org.jboss.aerogear.unifiedpush.service.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.commons.lang.RandomStringUtils;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.service.ClientInstallationService;
import org.jboss.aerogear.unifiedpush.service.SMSService;
import org.jboss.aerogear.unifiedpush.service.VerificationService;

@Singleton
public class VerificationServiceImpl implements VerificationService {

	private final static int VERIFICATION_CODE_LENGTH = 5;
	
	private ConcurrentMap<String, String> deviceToToken = new ConcurrentHashMap<>();
	
	@Inject
	private SMSService smsService;
	
	@Inject
	private ClientInstallationService clientInstallationService;
	
	@Override
	public String initiateDeviceVerification(Installation installation) {
		// create a random string made up of numbers
		String verificationCode = RandomStringUtils.random(VERIFICATION_CODE_LENGTH, false, true);
		smsService.sendSMS(installation.getAlias(), verificationCode);
		deviceToToken.put(installation.getDeviceToken(), verificationCode);
		return verificationCode;
	}

	@Override
	public VerificationResult verifyDevice(String variantID, String deviceToken, String verificationAttempt) {
		String code = deviceToToken.get(deviceToken);
		if (code == null) {
			return VerificationResult.UNKNOWN;
		} else if (code.equals(verificationAttempt)) {
			Installation installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID, deviceToken);
			installation.setEnabled(true);
			// TODO: there should be a "verifyDevice" like method in ClientInstallationService, which delegates here,
			// so implementations of VerificationService will not have to update the installation themselves.
			clientInstallationService.updateInstallation(installation);
			return VerificationResult.SUCCESS;
		}
		return VerificationResult.FAIL;
	}

}

@@ -1136,26 +1136,72 @@
 ;%0A%09%09
-deviceToToken.put(
+String key = buildKey(installation.getVariant().getVariantID(), 
 inst
@@ -1225,16 +1225,42 @@
 eToken()
+);%0A%09%09deviceToToken.put(key
 , verifi
@@ -1456,16 +1456,36 @@
 ken.get(
+buildKey(variantID, 
 deviceTo
@@ -1484,24 +1484,25 @@
 deviceToken)
+)
 ;%0A%09%09if (code
@@ -2107,12 +2107,122 @@
 FAIL;%0A%09%7D
+%0A%09%0A%09private String buildKey(String variantID, String deviceToken) %7B%0A%09%09return variantID + %22_%22 + deviceToken;%0A%09%7D
 %0A%0A%7D%0A

Add variant ID as part of the verification cache key