"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_native_1 = require("react-native");
const { DyteRNFileViewer } = react_native_1.NativeModules;
const eventEmitter = new react_native_1.NativeEventEmitter(DyteRNFileViewer);
let lastId = 0;
function open(path, options = {}) {
    const _options = typeof options === 'string' ? { displayName: options } : options;
    const { onDismiss } = _options, nativeOptions = __rest(_options, ["onDismiss"]);
    if (!['android', 'ios'].includes(react_native_1.Platform.OS)) {
        return DyteRNFileViewer.open(path, nativeOptions);
    }
    return new Promise((resolve, reject) => {
        const currentId = ++lastId;
        const openSubscription = eventEmitter.addListener('RNFileViewerDidOpen', ({ id, error }) => {
            if (id === currentId) {
                openSubscription.remove();
                return error ? reject(new Error(error)) : resolve({});
            }
        });
        const dismissSubscription = eventEmitter.addListener('RNFileViewerDidDismiss', ({ id }) => {
            if (id === currentId) {
                dismissSubscription.remove();
                onDismiss && onDismiss();
            }
        });
        DyteRNFileViewer.open(normalize(path), currentId, nativeOptions);
    });
}
function normalize(path) {
    if (react_native_1.Platform.OS === 'ios' || react_native_1.Platform.OS === 'android') {
        const filePrefix = 'file://';
        if (path.startsWith(filePrefix)) {
            path = path.substring(filePrefix.length);
            try {
                path = decodeURI(path);
            }
            catch (e) { }
        }
    }
    return path;
}
exports.default = { open };
//# sourceMappingURL=FileViewer.js.map