package ru.otus.mobile.driver;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import ru.otus.mobile.config.MobileConfig;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Singleton
public final class EmulatorQueue {
    private final BlockingQueue<MobileConfig.Emulator> queue;

    @Inject
    public EmulatorQueue(MobileConfig config) {
        this.queue = new LinkedBlockingQueue<>(config.emulators());
    }

    public MobileConfig.Emulator acquire() {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Interrupted while waiting for a free emulator.", e);
        }
    }

    public void release(MobileConfig.Emulator emulator) {
        if (!queue.offer(emulator)) {
            throw new IllegalStateException("Failed to return emulator back to the queue: " + emulator.id());
        }
    }
}
