package com.datarecovery.master.dialog;


import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

//todo 优化
public class DialogQueue {

    private static final String TAG = DialogQueue.class.getSimpleName();

    private static final Queue<BaseDialog<?>> dialogQueue = new PriorityQueue<>();

    private static final List<OnQueueStatusChangeCallback> callbacks = new ArrayList<>();

    private DialogQueue() {

    }

    public static void requestShow(BaseDialog<?> dialog) {
        dialogQueue.add(dialog);
        notifyDialogAdd();
        if (dialogQueue.size() == 1) {
            dialog.showInternal();
        }
    }

    public static void nextDialog() {
        BaseDialog<?> currentDialog = dialogQueue.poll();
        BaseDialog<?> nextDialog = dialogQueue.peek();
        if (nextDialog != null) {
            nextDialog.showInternal();
        } else {
            notifyQueueEmpty();
        }
    }

    public static boolean hasDialogShowing() {
        return !dialogQueue.isEmpty();
    }

    private static void notifyDialogAdd() {
        for (OnQueueStatusChangeCallback callback : callbacks) {
            if (callback != null) {
                callback.onDialogAdded();
            }
        }
    }

    private static void notifyQueueEmpty() {
        for (OnQueueStatusChangeCallback callback : callbacks) {
            if (callback != null) {
                callback.onQueueEmpty();
            }
        }
    }

    public static void registerQueueStatusCallback(OnQueueStatusChangeCallback callback) {
        if (callback == null) {
            return;
        }
        callbacks.add(callback);
    }

    public static void unregisterQueueStatusCallback(OnQueueStatusChangeCallback callback) {
        callbacks.remove(callback);
    }

    public interface OnQueueStatusChangeCallback {
        void onQueueEmpty();

        void onDialogAdded();
    }
}