package com.gingersoft.gsa.cloud.common.printer.plugins;

import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import io.reactivex.exceptions.UndeliverableException;
import io.reactivex.functions.Consumer;

/**
 * @作者: bin
 * @創建時間: 2021-01-25 9:46
 * @更新時間: 2021-01-25 9:46
 * @描述:
 */
public class PrintPaperPlugins {

    @Nullable
    static volatile Consumer<? super Throwable> errorHandler;

    @Nullable
    static volatile PrinterFlowListener onPrinterFlowHandler;

    public static void onError(@NonNull Throwable error) {
        Consumer<? super Throwable> f = errorHandler;
        if (error == null) {
            error = new NullPointerException("onError called with null");
        }
        if (f != null) {
            try {
                f.accept(error);
                return;
            } catch (Throwable e) {
                e.printStackTrace();
                uncaught(e);
            }
        }
        error.printStackTrace();
        uncaught(error);
    }

    static void uncaught(@NonNull Throwable error) {
        Thread currentThread = Thread.currentThread();
        Thread.UncaughtExceptionHandler handler = currentThread.getUncaughtExceptionHandler();
        handler.uncaughtException(currentThread, error);
    }

    public static void setErrorHandler(Consumer<? super Throwable> errorHandler) {
        PrintPaperPlugins.errorHandler = errorHandler;
    }

    public static PrinterFlowListener getOnPrinterFlowHandler() {
        if (onPrinterFlowHandler == null) {
            new NullPointerException("onPrinterFlowHandler called with null");
        }
        return onPrinterFlowHandler;
    }

    public static void setOnPrinterFlowHandler(PrinterFlowListener onPrinterFlowHandler) {
        PrintPaperPlugins.onPrinterFlowHandler = onPrinterFlowHandler;
    }
}
