import { concat, of } from "rxjs";
import { scan, switchMap } from "rxjs/operators";
import { updateFirmwareTask } from "../tasks/updateFirmware";
import { getDeviceInfoTask } from "../tasks/getDeviceInfo";
import { initialSharedActionState, sharedReducer } from "./core";
import { getLatestFirmwareTask } from "../tasks/getLatestFirmware";
export const initialState = {
    step: "preparingUpdate",
    progress: 0,
    ...initialSharedActionState,
};
/**
 * Device Action used to update the firmware installed on a Ledger device
 * @param deviceId the transport id of the device to be updated
 * @returns an Observables that emits the evolution of the state machine of the firmware installation
 */
export function updateFirmwareAction({ deviceId, deviceName, }) {
    return concat(of(initialState), getDeviceInfoTask({ deviceId, deviceName }).pipe(switchMap(event => {
        if (event.type !== "data") {
            return of(event);
        }
        const { deviceInfo } = event;
        return getLatestFirmwareTask({ deviceId, deviceName, deviceInfo });
    }), switchMap(event => {
        if (event.type !== "data") {
            return of(event);
        }
        else {
            return updateFirmwareTask({
                deviceId,
                deviceName,
                updateContext: event.firmwareUpdateContext,
            });
        }
    }), scan((currentState, event) => {
        switch (event.type) {
            case "taskError":
                return {
                    ...currentState,
                    error: {
                        type: "UpdateFirmwareError",
                        name: event.error,
                    },
                };
            case "installingOsu":
            case "flashingMcu":
            case "flashingBootloader":
                return {
                    ...initialState,
                    step: event.type,
                    progress: event.progress,
                };
            case "allowSecureChannelRequested":
            case "allowSecureChannelDenied":
            case "installOsuDevicePermissionRequested":
            case "installOsuDevicePermissionGranted":
            case "installOsuDevicePermissionDenied":
                return { ...initialState, step: event.type };
            case "firmwareUpdateCompleted":
                return {
                    ...initialState,
                    step: event.type,
                    updatedDeviceInfo: event.updatedDeviceInfo,
                };
            default:
                return {
                    ...currentState,
                    ...sharedReducer({
                        event,
                    }),
                };
        }
    }, initialState)));
}
//# sourceMappingURL=updateFirmware.js.map