/*
 * 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.sdm.application.service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.stereotype.Service;

/**
 * Service that handles if a certain ID is performing any operation
 */
@Service
public class IdleStatusService {

	private final ConcurrentHashMap<String, AtomicBoolean> idleStatusIds = new ConcurrentHashMap<>();

	/**
	 * Checks if the id is ready for executing an operation. The purpose is to avoid parallel executions due to extra
	 * quickly clicks on the front end
	 * 
	 * @param id
	 * @return
	 */
	public synchronized boolean isIdReady(String id) {
		if (idleStatusIds.containsKey(id)) {
			return idleStatusIds.get(id).compareAndSet(false, true);
		} else {
			AtomicBoolean atomicBoolean = new AtomicBoolean(true);
			idleStatusIds.put(id, atomicBoolean);
			return true;
		}

	}

	/**
	 * Marks the id as ready to be executed
	 * 
	 * @param id
	 */
	public void freeIdleStatus(String id) {
		idleStatusIds.get(id).set(false);
	}

}
