/*
 * 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.ov.mixing.core;

import javax.annotation.Nonnegative;

/**
 * Listener that can be used for monitoring the state and progress of a job.
 */
public final class JobStateAndProgressListener implements JobEventListener {

    private int progress;

    private JobState jobState;

    /**
     * Initialize the listener.
     * <p>
     * Note: the state and progress will not be initialized until the appropriate methods are called.
     */
    public JobStateAndProgressListener() {
        progress = 0;
    }

    @Override
    public void progressChanged(JobEvent jobEvent) {
        progress = jobEvent.getSource().progress();
    }

    @Override
    public void stateChanged(JobEvent jobEvent) {
        jobState = jobEvent.getSource().state();
    }

    /**
     * Returns the progress.
     *
     * @return the progress.
     */
    @Nonnegative
    public int progress() {
        return progress;
    }

    /**
     * Returns the state.
     *
     * @return the state.
     * @throws IllegalStateException
     *             if the state has not yet been initialized.
     */
    public JobState state() {
        if (jobState == null) {
            throw new IllegalStateException("The state has not yet been initialized");
        }
        return jobState;
    }
}
