import { Observable, Subject, of, takeUntil } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { DeviceActionStatus, DeviceLockedError, UserInteractionRequired, } from "@ledgerhq/device-management-kit";
import { DisconnectedDevice } from "@ledgerhq/errors";
export class PrepareConnectManagerEventMapper {
    events;
    eventSubject = new Subject();
    constructor(events) {
        this.events = events;
    }
    map() {
        const cancelAction = this.events.cancel;
        const unsubscribe = new Subject();
        // Subscribe to device action events
        this.events.observable
            .pipe(tap(event => this.handleEvent(event)), takeUntil(unsubscribe), catchError(error => this.handleError(error)))
            .subscribe();
        return new Observable(observer => {
            const sub = this.eventSubject.subscribe(observer);
            return () => {
                sub.unsubscribe();
                cancelAction();
                unsubscribe.next();
            };
        });
    }
    handleEvent(event) {
        switch (event.status) {
            case DeviceActionStatus.Pending:
                this.handlePendingEvent(event.intermediateValue);
                break;
            case DeviceActionStatus.Completed:
                this.handleCompletedEvent(event.output);
                break;
            case DeviceActionStatus.Error:
                this.handleErrorEvent(event.error);
                break;
            case DeviceActionStatus.NotStarted:
            case DeviceActionStatus.Stopped:
                this.eventSubject.error(new Error("Unexpected device action status"));
                break;
        }
    }
    handlePendingEvent(intermediateValue) {
        switch (intermediateValue.requiredUserInteraction) {
            case UserInteractionRequired.UnlockDevice:
                this.eventSubject.next({ type: "lockedDevice" });
                break;
            case UserInteractionRequired.None:
                // Nothing to do
                break;
        }
    }
    handleCompletedEvent(_output) {
        this.eventSubject.complete();
    }
    handleErrorEvent(error) {
        if (error instanceof DeviceLockedError) {
            this.eventSubject.next({ type: "lockedDevice" });
            this.eventSubject.complete();
        }
        else if ("_tag" in error && error._tag === "WebHidSendReportError") {
            this.eventSubject.error(new DisconnectedDevice());
        }
        else {
            this.eventSubject.error(error);
        }
    }
    handleError(error) {
        this.eventSubject.error(error);
        return of();
    }
}
//# sourceMappingURL=connectManagerEventMapper.js.map