import { scan, tap } from "rxjs/operators";
import { useCallback, useEffect, useState } from "react";
import { log } from "@ledgerhq/logs";
import { useReplaySubject } from "../../observable";
import { currentMode } from "./app";
import { getImplementation } from "./implementations";
const mapResult = ({ imageRemoved }) => imageRemoved;
const getInitialState = (device) => ({
    isLoading: !!device,
    requestQuitApp: false,
    unresponsive: false,
    device,
    deviceInfo: null,
    error: null,
    imageRemoveRequested: false,
    imageRemoved: false,
});
const reducer = (state, e) => {
    switch (e.type) {
        case "unresponsiveDevice":
            return { ...state, unresponsive: true, isLoading: false };
        case "deviceChange":
            return getInitialState(e.device);
        case "error":
            return {
                ...state,
                error: e.error,
                isLoading: false,
            };
        case "removeImagePermissionRequested":
            return {
                ...state,
                unresponsive: false,
                imageRemoveRequested: true,
                isLoading: false,
            };
        case "imageRemoved":
            return {
                ...state,
                unresponsive: false,
                imageRemoveRequested: false,
                isLoading: false,
                imageRemoved: true,
            };
    }
};
export const createAction = (task) => {
    const useHook = (device, _) => {
        const [state, setState] = useState(() => getInitialState(device));
        const [resetIndex, setResetIndex] = useState(0);
        const deviceSubject = useReplaySubject(device);
        const onRetry = useCallback(() => {
            setResetIndex(currIndex => currIndex + 1);
            setState(s => getInitialState(s.device));
        }, []);
        useEffect(() => {
            if (state.imageRemoved)
                return;
            const impl = getImplementation(currentMode)({
                deviceSubject,
                task,
                request: {},
            });
            const sub = impl
                .pipe(tap((e) => log("actions-remove-custom-lock-screen-event", e.type, e)), scan(reducer, getInitialState()))
                .subscribe(setState);
            return () => {
                sub.unsubscribe();
            };
        }, [deviceSubject, resetIndex, state.imageRemoved]);
        return {
            ...state,
            onRetry,
        };
    };
    return {
        useHook,
        mapResult,
    };
};
//# sourceMappingURL=customLockScreenRemove.js.map