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

import org.apache.commons.lang3.StringUtils;

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.validation.commons.progress.JobProgressDetails;


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 registerJob(final String jobId, final JobProgressDetails job) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        registerJob(UUID.fromString(jobId), job);
    }

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

    @Override
    public void unregisterJob(final String jobId) {
        if(StringUtils.isNotBlank(jobId)) {
            unregisterJob(UUID.fromString(jobId));
        }
    }

    @Override
    public Optional<JobProgressDetails> getJobProgress(final UUID jobId) {
        if( jobId != null ) {
            return Optional.ofNullable(jobMap.get(jobId));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public Optional<JobProgressDetails> getJobProgress(final String jobId) {
        if(StringUtils.isNotBlank(jobId)) {
            return getJobProgress(UUID.fromString(jobId));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public void updateJobProgress(final UUID jobId, final long deltaValue) {
        Objects.requireNonNull(jobId, "jobId cannot be null");
        getJobProgress(jobId).ifPresent(jpd -> jpd.incrementWorkCompleted(1));
    }
}
