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

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

public class JobProgressDetails {

    public static final JobProgressDetails EMPTY = new JobProgressDetails(new UUID(0,0),-1L);
    private long totalWorkAmount;
    private AtomicLong workCompleted;
    private UUID id;
    private Instant start;

    private JobProgressDetails(){ }

    public JobProgressDetails(UUID jobId, long totalWorkAmount) {
        this.id = jobId;
        this.totalWorkAmount = totalWorkAmount;
        this.workCompleted = new AtomicLong(0);
        this.start = Instant.now();
    }

    public long getTotalWorkAmount() {
        return totalWorkAmount;
    }

    public long getRemainingWork() {
        return totalWorkAmount - workCompleted.get();
    }

    public long incrementWorkCompleted(long amountCompleted) {
        return workCompleted.addAndGet(amountCompleted);
    }

    public long getEstimatedTimeToCompletionInMillis() {
        Duration runningTime = Duration.between(start, Instant.now());
        final long currentWorkCompleted = workCompleted.get();
        if(currentWorkCompleted <= 0) {
            return -1L;
        }
        final long avgItemsPerMilli = Math.floorDiv(runningTime.toMillis(), currentWorkCompleted);
        return getRemainingWork() * avgItemsPerMilli;
    }

    @Override
    public String toString() {
        return id.toString() + " : "+Long.toString(getTotalWorkAmount());
    }
}
