package eu.dnetlib.functionality.modular.ui.utils;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;

import eu.dnetlib.enabling.common.Stoppable;
import eu.dnetlib.enabling.common.StoppableDetails;
import eu.dnetlib.enabling.common.StoppableDetails.StopStatus;

public class ShutdownUtils {

	@Autowired(required = false)
	private List<Stoppable> stoppables = Lists.newArrayList();

	private StopStatus status = StopStatus.RUNNING;

	private static final Log log = LogFactory.getLog(ShutdownUtils.class);

	public List<StoppableDetails> listStoppableDetails() {
		final List<StoppableDetails> list = Lists.newArrayList();

		for (Stoppable s : stoppables) {
			list.add(s.getStopDetails());
		}

		return list;
	}

	public void stopAll() {
		this.status = StopStatus.STOPPING;

		for (Stoppable s : stoppables) {
			final StoppableDetails info = s.getStopDetails();
			if (info.getStatus() == StopStatus.RUNNING) {
				log.info("Stopping " + info.getName());
				s.stop();
			}
		}
	}

	public void resumeAll() {
		for (Stoppable s : stoppables) {
			final StoppableDetails info = s.getStopDetails();
			if (info.getStatus() != StopStatus.RUNNING) {
				log.info("Resuming " + info.getName());
				s.resume();
			}
		}
		this.status = StopStatus.RUNNING;
	}

	public StopStatus currentStatus() {
		if (status == StopStatus.STOPPING) {
			int running = 0;
			for (Stoppable s : stoppables) {
				final StoppableDetails info = s.getStopDetails();
				if (info.getStatus() != StopStatus.STOPPED) {
					running++;
				}
			}
			if (running == 0) {
				status = StopStatus.STOPPED;
			}
		}
		return status;
	}
}
