"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAppData = void 0;
const rxjs_1 = require("rxjs");
const types_1 = require("./types");
function deleteAppData(appName, deviceModelId, storageProvider) {
    const obs = new rxjs_1.Observable(subscriber => {
        subscriber.next({ type: types_1.DeleteAppDataEventType.AppDataDeleteStarted });
        const sub = (0, rxjs_1.from)(storageProvider.getItem(`${deviceModelId}-${appName}`))
            .pipe((0, rxjs_1.switchMap)(async (item) => {
            if (item) {
                try {
                    await storageProvider.removeItem(`${deviceModelId}-${appName}`);
                    subscriber.next({ type: types_1.DeleteAppDataEventType.AppDataDeleted });
                    subscriber.complete();
                }
                catch (e) {
                    const message = e instanceof Error ? e.message : "Error deleting app data";
                    throw new types_1.DeleteAppDataError(message);
                }
            }
            else {
                subscriber.next({ type: types_1.DeleteAppDataEventType.NoAppDataToDelete });
                subscriber.complete();
            }
        }), (0, rxjs_1.catchError)(e => {
            if (e instanceof Error || e instanceof types_1.DeleteAppDataError) {
                subscriber.error(e);
            }
            else {
                subscriber.error(new Error("Unknown error"));
            }
            return (0, rxjs_1.of)(null);
        }))
            .subscribe();
        return () => {
            subscriber.complete();
            sub.unsubscribe();
        };
    });
    return obs;
}
exports.deleteAppData = deleteAppData;
//# sourceMappingURL=deleteAppData.js.map