/*
 * 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.config.commands.progress;

import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.scytl.products.ov.config.commons.progress.JobProgressDetails;

@Component
public class ProgressManagerImpl implements ProgressManager {

    private final ConcurrentMap<UUID, JobProgressDetails> jobMap = new ConcurrentHashMap<>();

    @Override
    public void registerJob(final UUID jobId, final JobProgressDetails job) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        jobMap.put(jobId, job);
    }

    @Override
    public void unregisterJob(final UUID jobId) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        jobMap.remove(jobId);
    }

    @Override
    public Optional<JobProgressDetails> getJobProgress(final UUID jobId) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        return Optional.ofNullable(jobMap.get(jobId));
    }

    @Override
    public void updateProgress(final UUID jobId, final double deltaValue) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        getJobProgress(jobId).ifPresent(jobProgress -> jobProgress.incrementWorkCompleted(deltaValue));
    }
}
